gpt4 book ai didi

reactjs - react : Children onclick to change parent's state for re-rendering

转载 作者:行者123 更新时间:2023-12-03 13:21:00 25 4
gpt4 key购买 nike

我对 React 还很陌生。我试图让家长根据州更改显示的页面。我的子组件中有一个按钮,它应该向父组件发送“true”或“false”,以便它知道是否渲染它。我认为应该用这样的 Prop 来完成:

this.state = {
btnNewScreen: this.props.btnNewScreen //true or false
};

但我无法让它发挥作用。你能给一些建议吗?这是完整的父-子

父级 - maindisplay.js

import React from 'react';
import Mainpage_Addscreen from '../components/subcomponents/mainpage-addscreen';
import Mainpage_Showscreens from '../components/subcomponents/mainpage-showscreens';
//
class MainDisplay extends React.Component {
constructor() {
super();
this.state = {
btnNewScreen: false //should be this.props.btnNewScreen?
};
}

render() {
var renderThis;
if (!this.state.btnNewScreen) {
renderThis =
<div>
<Mainpage_Addscreen />
<Mainpage_Showscreens />
</div>
}
else {
//renderThis = <AddScreen />
renderThis =
<div>
<Mainpage_Addscreen />
<h3>Change to this when true (button click)</h3>
</div>
}
return (
<div>
{renderThis}
</div>
);
}
}


export default MainDisplay;

子-mainpage-addscreen.js

import React from 'react';

import Glyphicon from 'react-bootstrap/lib/Glyphicon';
import Button from 'react-bootstrap/lib/Button';

class Mainpage_Addscreen extends React.Component {
constructor() {
super();
this.state = {
btnNewScreen: true
};
this.newScreen = this.newScreen.bind(this);
}

newScreen(e) {
this.setState({ btnNewScreen: !this.state.btnNewScreen });
console.log(this.state.btnNewScreen);
}
render() {
var text = this.state.btnNewScreen ? 'Add new' : 'Screens';
return (
<div className="main_window col-sm-offset-1 col-sm-10">
<h3 id="addscreens">Screens: </h3>
<Button id="addScreen" className="btn btn-primary dropdown-toggle" type="button" data-toggle="dropdown" onClick={this.newScreen}><Glyphicon id="refresh_screens" glyph="plus" />&nbsp; {text}</Button>
</div>
);
}
}


export default Mainpage_Addscreen;

最佳答案

您需要做的是将一个方法从父级传递给子级,该方法可以在单击按钮时调用。这个属于父级的方法将改变状态。
在 MainPage.js 中

changeButtonState(event) {
this.setState({btnNewScreen: !this.state.btnNewScreen})
}

将此方法传递给您的子组件

<Mainpage_Addscreen buttonClick={this.changeButtonState.bind(this)} />

最后在子组件中,

<Button ....   onClick={this.props.buttonClick} />

关于reactjs - react : Children onclick to change parent's state for re-rendering,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38894745/

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