如果有多个组件和唯一的公共父组件,我需要了解如何将类的状态和方法提升到父组件。在我的代码示例中,一些按钮显示为“ li”列表 元素。单击任何按钮应会更改文本块中的文本,但不会更改。请帮我找到我的错误。这是我的代码:
class TextBlock extends React.Component {
render() {
return <div id="textDiv">{this.props.text}</div>;
}
}
class MyButton extends React.Component {
render() {
return <button id={this.props.id} className="mybutton">
{this.props.label}</button>;
}
}
class ButtonsList extends React.Component {
clickButton=(e)=> {
this.props.handlerButtons(e);
}
render() {
return(
<ul>
{buttons.map((button)=> <MyButton id={button.id} label=
{button.label} onClick={this.clickButton}/>)}
</ul>
);
}
}
class ParentComponent extends React.Component {
constructor(props) {
super(props);
this.state={text: "My text"};
}
handlerButtons=(e)=> {
this.setState({text: "The changed text"});
}
render() {
return( <div>
<TextBlock text={this.state.text}/>
<ButtonsList handlerButtons={this.handlerButtons}/>
</div>
);
}
}
const buttons=[{id: "id1", label: "1"}, {id: "id2", label: "2"},
{id: "id3", label: "3"}, {id: "id4", label: "4"}, {id: "id5", label: "5"}];
ReactDOM.render(
<ParentComponent/>,
document.getElementById("root")
);
答案 0 :(得分:0)
您需要在MyButton组件中缺少的按钮上添加onClick
class MyButton extends React.Component {
render() {
return <button id={this.props.id} className="mybutton" onClick={this.props.onClick}>
{this.props.label}</button>;
}
}