我在应用程序中的目标是,当单击按钮时,将操作设置为新的并提供给子组件。一旦子组件收到这个值,它就应该显示来自 div 的文本。在进一步的实施中,我将添加另一个按钮,单击此按钮时,它将设置要编辑的操作。子组件应该自动接收值并基于此返回另一个 div。
let actionToPerform = "";
function actionState(action){
if(action === 'new'){
actionToPerform = 'new'
}else{
actionToPerform = 'edit'
}
}
<button onClick={() => actionState('new')}>Create new Shoppinglist</button>
<button onClick={() => actionState('edit')}>Edit Shoppinglist</button>
<Edit action={actionToPerform}/>
子组件:
export default class Edit extends React.Component {
constructor(props){
super(props);
this.state = {actionToPerform: this.props.action}
}
showTitle() {
if(this.state.actionToPerform === 'new'){
return <div>new Shoppinglist</div>
}else if(this.state.actionToPerform === 'edit'){
return <div>edit</div>
}else{
return <div>nothing to show</div>
}
}
render() {
return (
this.showTitle()
)
}
}
我知道我应该以某种方式使用 componentDidMount 和 componentUpdate 来实现这一点,但我无法做到。现在,在加载页面时,它会触发 onClick 操作,我不知道为什么。当我点击按钮时,没有其他事情发生