【发布时间】:2017-12-25 22:53:00
【问题描述】:
我是 ReactJS 的新手。
我想问你一个简单的问题。
当孩子被更改后,我如何更新其他孩子?
谢谢!
。 enter image description here .
以下sn -p的代码供参考。
class Parent extends React.Component {
constructor(props) {
super(props);
this.state = {
fieldVal: "Default Value",
}
}
onUpdate = (val) => {
this.setState({
fieldVal: val,
})
};
render() {
return (
<div>
<h2>Parent</h2>
Value in Parent Component State: {this.state.fieldVal}
<br/>
<Child passedVal={this.state.fieldVal} onUpdate={this.onUpdate} />
<br />
<OtherChild passedVal={this.state.fieldVal} onUpdate={this.onUpdate} />
</div>
)
}
}
class Child extends React.Component {
constructor(props) {
super(props);
this.state = {
fieldVal: props.passedVal,
}
}
update = (e) => {
this.props.onUpdate(e.target.value);
this.setState({fieldVal: e.target.value});
};
render() {
return (
<div>
<h4>Child</h4>
<p>Value in Child: {this.state.fieldVal}</p>
<input
type="text"
placeholder="type here"
onChange={this.update}
value={this.state.fieldVal}
/>
</div>
)
}
}
class OtherChild extends React.Component {
constructor(props) {
super(props);
this.state = {
fieldVal: this.props.passedVal,
}
}
update = (e) => {
this.props.onUpdate(e.target.value);
this.setState({fieldVal: e.target.value});
};
render() {
return (
<div>
<h4>OtherChild</h4>
<p>Value in OtherChild: {this.state.fieldVal}</p>
<input
type="text"
placeholder="type here"
onChange={this.update}
value={this.state.fieldVal}
/>
</div>
)
}
}
React.render(
<Parent />,
document.getElementById('react_example')
);
<!DOCTYPE html>
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.0/react-dom.min.js"></script>
<meta charset="utf-8">
<title>React Hello World w/ JSBin</title>
</head>
<body>
<div id="react_example"></div>
</body>
</html>
【问题讨论】:
-
因为两者都使用
fieldVal,这应该导致它们按原样重新渲染?问题是您绑定到this.state.value并且应该绑定到道具,或者您应该监听道具更改并更新您的状态。例如componentWillRecieveProps(newProps){ if (this.state.fieldValue !== newProps.passedVal) this.setState({fieldVal: newProps.passedVal}) }- 你应该阅读受控输入而不是:facebook.github.io/react/docs/uncontrolled-components.html -
@DimitarChristoff 非常感谢。
标签: reactjs