gpt4 book ai didi

javascript - 使用 setstate 调用父回调时, react 子组件无法呈现

转载 作者:太空宇宙 更新时间:2023-11-04 15:35:05 25 4
gpt4 key购买 nike

我有一个父/子组件:

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,子组件就不再正确呈现。为什么?它与事件对象或从子事件处理程序调用父事件处理程序的事实有关吗?

最佳答案

使用这个(在之前和之后添加空格?):

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')
);
<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>

关于javascript - 使用 setstate 调用父回调时, react 子组件无法呈现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44438553/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com