gpt4 book ai didi

javascript - React - 调用父组件中的函数来访问状态

转载 作者:行者123 更新时间:2023-11-28 17:25:45 24 4
gpt4 key购买 nike

我试图构建一个简单的计算器应用程序来开始使用 React。我试图从子组件中调用根组件中的函数来访问当前状态。我能够调用该函数,但无法访问状态,因为我想更新状态。下面是我的代码:

class App extends React.Component {
constructor(props) {
super(props);
this.state = {
count: 0,
numbers: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
actions: ['=','+','-','*','/','.','C']
}
}


appendThisNumber(number,oldcount){
let newCount=parseInt(oldcount.toString()+number.toString());
console.log('New number '+newCount);
//below code errors out
this.setState({
count:newCount
});

};
performThisAction(action, oldcount){
// stuff to do
};
render() {

return (
<div>
<CounterDiv countNow={this.state.count} />
<div>
{this.state.numbers.map((n) => <NumButton NumValue={n} countNow={this.state.count} onClickFunction={this.appendThisNumber}/>)}
</div>
<div>
{this.state.actions.map((a) => <ActionButtons actionItem={a} countNow={this.state.count} onClickFunction={this.performThisAction}/>)}
</div>

</div>
);
}
}


class CounterDiv extends React.Component {
render() {
return (
<div>
<input type='text' readOnly value={this.props.countNow} />
</div>
);
}
}

class NumButton extends React.Component {
handleClick(){
this.props.onClickFunction(this.props.NumValue,this.props.countNow);
}

render() {
return (
<button onClick={()=>this.handleClick()} value={this.props.NumValue}>{this.props.NumValue}</button>
);
}
}

class ActionButtons extends React.Component{
handleClick(){
this.props.onClickFunction(this.props.actionItem,this.props.countNow);
}
render() {
return (
<button onClick={()=>this.handleClick()} value={this.props.actionItem} label={this.props.actionItem}>{this.props.actionItem}</button>
);
}
}
export default App;

我做错了什么或者我需要使用一些数据绑定(bind)框架吗?提前致谢

最佳答案

您需要将 appendThisNumber() 绑定(bind)到 this

在构造函数中将其绑定(bind)为:

 this.appendThisNumber = this.appendThisNumber.bind(this);

关于javascript - React - 调用父组件中的函数来访问状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51647975/

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