gpt4 book ai didi

javascript - React 子组件的状态未定义

转载 作者:行者123 更新时间:2023-12-02 14:21:42 25 4
gpt4 key购买 nike

我有一个父组件 PlanList:

class PlanList extends Component {
constructor(props) {
super(props);
this.renderPlans = this.renderPlans.bind(this);
this.planListFilter = <PlanListFilter onChange={this.handleFilterChange.bind(this)} />
}

loadPlans() {
console.log(this.planListFilter);
// returns: Object {$$typeof: Symbol(react.element), key: null, ref: null, props: Object, _owner: ReactCompositeComponentWrapper…}

console.log(this.planListFilter.state);
// returns: undefined
// I expect it to return the state object i defined in the PlanListFilter constructor

// here I would apply the filters to the PlanTable
}

handleFilterChange(event) {
this.loadPlans();
}

render() {
return (
<div className="PlanList">
{this.planListFilter}
<PlanTable />
</div>
)
}
}

和一个子组件 PlanListFilter:

class PlanListFilter extends Component {
constructor(props) {
super(props);
this.state = {
search: '',
};
this.handleSearchChange = this.handleSearchChange.bind(this);
}

handleSearchChange(event) {
this.setState({search: event.target.value});
this.props.onChange(event);
}

render() {
return (
<FormControl type="text" placeholder="Search" onChange={this.handleSearchChange} value={this.state.search} />
);
}
}

更改 FormControl 上的文本时,onChange 属性会按预期触发,但在父对象中,子对象的 stateundefined。我希望它会填充正确的状态。

最佳答案

在 React 数据流向一个方向时,如果您的父级应该知道子级的更改,则必须将处理程序作为 prop 传递给子级,以便从子级内部调用它。

class Papa extends React.Component {
constructor(p, c) { super(p, c) }
handleFilterChange(valueFromChild) {
//
}
render() {
return <Child filterHandler={this.handleFilterChange} />
}
}

const Child = ({filterHanlder}) => (
<button onClick={() => filterHandler('valueToParent') } >Click Me</button>
)

关于javascript - React 子组件的状态未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38599055/

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