我正在尝试在React Storybook(link)上测试我的UI组件。但是,我想添加一个按钮,所以当我按下它时,它会将新的props传递给已经渲染的组件(因此触发生命周期方法componentWillReceiveProps)。但是,我不知道该怎么做。我将非常感谢您的帮助,谢谢。
答案 0 :(得分:1)
您需要找到该按钮的第一个共享父级以及您尝试触发componentWillReceiveProps
的组件。
例如,假设您的结构如下所示:
<SomeComponent>
<AnotherComponent someProp={someValue} />
<AThirdComponent>
<button />
</AThirdComponent>
</SomeComponent>
SomeComponent
是AnotherComponent
和button
的第一个共享父级。
找到共享父级后,添加一些状态和方法:
class SomeComponent extends React.Component {
constructor(props) {
super(props);
this.updateButton = this.updateButton.bind(this);
this.state = { buttonWasClicked: false };
}
updateButton() {
this.setState({ buttonWasClicked: true});
}
}
现在将updateButton
方法向下传递到AThirdComponent
中的按钮,并将状态附加到AnotherComponent
:
render() { // SomeComponent's render method
return (
<div>
<AnotherComponent buttonWasClicked={this.state.buttonWasClicked} />
<AThirdComponent updateButton={this.updateButton}`/>
</div>
);
}
在AThirdComponent
中,将updateButton处理程序附加到按钮:
<button onClick={this.props.updateButton} />
现在,当您点击该按钮时,SomeComponent
的状态将会更新,导致它将新道具传递给AnotherComponent
。