我有一个父/子组件:
class Input extends React.Component {
constructor(props) {
super(props);
this.state = {value: this.props.value};
this.handleChange = this.handleChange.bind(this);
}
handleChange(e) {
// event is persisted, used to update local state
// and then call parent onChange callback after local state update
e.persist();
this.setState(
{value: e.target.value},
() => this.props.onChange(e)
);
}
render() {
return (<input ... onChange={this.handleChange} />);
}
}
class Page extends React.Component {
constructor(props) {
super(props);
this.state = {modified: false};
this.handleChange = this.handleChange.bind(this);
}
handleChange(e) {
const {name, value} = e.target;
console.log(`${name}: ${value}`);
// the two line execute fine, and everything works ok
// but as soon as I add the bottom on, Input no longer updates!
this.setState({modified: true});
}
render() {
return (
<Input ... onChange={this.handleChange}
style={{backgroundColor: this.state.modified?"red":"blue"}}
/>
);
}
}
因此,只要在父级上执行setState,子组件就不再正确呈现。为什么?它是否与事件对象或从子事件处理程序调用父事件处理程序这一事实有关?
答案 0 :(得分:1)
使用此方法(在?
之前和之后添加空格):
style={{backgroundColor: this.state.modified ? "red" : "blue"}}
而不是:
style={{backgroundColor: this.state.modified?"red":"blue"}}
在此更改后,您的示例正常工作:
class Input extends React.Component {
constructor(props) {
super(props);
this.state = {value: this.props.value};
this.handleChange = this.handleChange.bind(this);
}
handleChange(e) {
// event is persisted, used to update local state
// and then call parent onChange callback after local state update
e.persist();
this.setState(
{value: e.target.value},
() => this.props.onChange(e)
);
}
render() {
return (<input style={this.props.style} onChange={this.handleChange} />);
}
}
class Page extends React.Component {
constructor(props) {
super(props);
this.state = {modified: false};
this.handleChange = this.handleChange.bind(this);
}
handleChange(e) {
const {name, value} = e.target;
console.log(`${name}: ${value}`);
// the two line execute fine, and everything works ok
// but as soon as I add the bottom on, Input no longer updates!
this.setState({modified: true});
}
render() {
return (
<Input onChange={this.handleChange}
style={{backgroundColor: this.state.modified ? "red":"blue"}}
/>
);
}
}
ReactDOM.render(
<Page />,
document.getElementById('container')
);
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="container">
<!-- This element's contents will be replaced with your component. -->
</div>
&#13;