我试图弄清楚如何在仅使用prop的无状态组件中设置禁用字段。无状态组件具有一个输入字段,如果为空,我想禁用同一组件内的提交按钮。我能够通过给孩子的道具来更新父母的状态,因此想保持它没有任何状态,但是开始认为我可能需要它来检查按钮是否可以启用。
我尝试了使用refs等的不同方法。这是我有一个示例的codeandbox项目
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>
);
};
谢谢
答案 0 :(得分:1)
我只将本地状态用于输入值。这将使其成为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>
);
}
};
答案 1 :(得分:0)
无法完成。您的应用程序中的某些内容必须调用DECLARE @table TABLE (
time int
,value int
, group_id int
)
INSERT INTO @table ( time , value )
SELECT time , value
FROM [your_table_name]
UPDATE t
SET group_id = CEILING(t.id/3.0)
FROM @table as t
SELECT id , value , group_id
FROM (
SELECT
id
, value
, group_id
, rank() OVER (PARTITION BY group_id ORDER BY value DESC) AS r
FROM @table ) As x
WHERE x.r = 1;
,setState
或重新渲染根应用程序,才能再次调用您的无状态函数。
答案 2 :(得分:0)
您可以按以下方式使其工作:https://codesandbox.io/s/rr6jw0xxko
唯一的问题是禁用按钮后,由于无法再提交,因此无法再次启用它。
我同意@azium方式是React方式。