我试图弄清楚如何在仅使用 prop 的无状态组件中设置禁用字段。无状态组件有一个输入字段,如果为空,我想禁用同一组件中的提交按钮。我能够通过子项的 Prop 来更新父项的状态,因此希望保持它没有状态,但开始认为我可能需要它来检查按钮是否可以启用。
我尝试了使用 refs 等不同的方法。这是我的一个示例代码和盒子项目
https://codesandbox.io/s/840kkk03l
无状态属性是:
const Childprop = function(props) {
function handleNameChange(e) {
e.preventDefault();
props.onNameChange(e.target.newName.value);
}
function checkDisabled() {
var input = document.getElementById("input");
if (input.value === "") {
return true;
} else {
return false;
}
}
return (
<p>
The logged in user is: {props.nameProp}
<form onSubmit={handleNameChange}>
<input name="newName" type="text" id="input" />
<input type="submit" disabled={checkDisabled} />
</form>
</p>
);
};
谢谢
最佳答案
我将仅使用本地状态作为输入的值。这将使其成为 controlled component .
class Childprop extends React.Component {
state = {
newName: ''
}
handleNameChange = (e) => {
e.preventDefault();
props.onNameChange(this.state.newName);
this.setState({ newName: '' });
}
render() {
return (
<div>
The logged in user is: {props.nameProp}
<form onSubmit={handleNameChange}>
<input name="newName" type="text" id="input" onChange={(e) => this.setState(e.target.value)} value={this.state.newName} />
<input type="submit" disabled={this.state.newName.length === 0} />
</form>
</div>
);
}
};
关于javascript - 禁用无状态组件中的按钮 - React,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51902086/