因此,要详细说明我之前的回复,您将执行以下操作来实现您想要的:
@connect(...)
class Some extends React.Component {
constructor(props) {
super(props);
this.state = {
value: '',
}
}
handleChange = (event) => {
this.setState({ value: event.target.value });
}
render() {
return(
<div>
<input onChange={this.handleChange} id="some" type="text" value= {this.state.value|| this.props.value}/>
</div>
)
}
}
虽然您的值是一个空字符串(在该州),但这些字段将从您的道具中填充,并且一旦您开始输入,它将用您所在州的值覆盖预填充的值。
最佳实践是实际拥有一个处理此逻辑的组件,然后将道具传递给应该只是一个愚蠢的演示组件的表单:
class SomeController extends React.Component {
constructor(props) {
super(props);
this.state = {
value: '',
}
}
handleChange = (event) => {
this.setState({ value: event.target.value });
}
return (<Form handleChange={this.handleChange} value={this.state.value} />)
}
然后你的表单组件:
const Form = (props) => (
<form>
<input onChange={props.handleChange} value={props.value} />
</form>
);
希望这个解释有所帮助。