通过父组件的 onClick 更新组件状态

IT技术 javascript reactjs components
2021-04-28 05:58:54

我在应用程序中的目标是,当单击按钮时,操作设置为新的并提供给子组件。一旦子组件接收到这个值,它就应该显示来自 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 操作,我不知道为什么。当我点击按钮时,没有其他react

2个回答

父组件:

当您更新actionToPerform您的组件不知道这一点并且它不会重新渲染时,您需要将它保留在它的state

state = {
  actionToPerform: ""
}

updateState(actionToPerform){
    this.setState({ actionToPerform })
}

<button onClick={() => this.updateState('new')}>Create new Shoppinglist</button>
<button onClick={() => this.updateState('edit')}>Edit Shoppinglist</button>
<Edit action={actionToPerform}/>

现在,当您单击其中一个按钮时,状态的值会更新并且组件会重新呈现,并将新值传递给子组件。

子组件:

您不应该从 设置状态的初始值props,请参阅反模式:无条件地将props复制到状态

您甚至可以将其全部删除,因为您可以根据props进行条件渲染

export default class Edit extends React.Component {
  render() {
    return this.props.actionToPerform === "new" ? (
      <div>new Shoppinglist</div>
    ) : this.props.actionToPerform === "edit" ? (
      <div>edit</div>
    ) : (
      <div>nothing to show</div>
    );
  }
}

Edit您应该使用parentt组件中的状态并将该状态作为props传递给子(编辑)组件并使用它,而不是在组件中使用状态

父.js

actionState = (action) => {
   if(action === 'new'){
      this.setState({ actionToPerform: 'new' })
   } else{
      this.setState({ actionToPerform: 'edit' })
   }
}
render() {
 return (
   <div>
     <button onClick={() => this.actionState('new')}>Create new Shoppinglist</button>
     <button onClick={() => this.actionState('edit')}>Edit Shoppinglist</button>
     <Edit action={this.state.actionToPerform}/>
   </div>
 )
}

child.js

export default class Edit extends React.Component {

    showTitle() {
        if(this.props.actionToPerform === 'new'){
            return <div>new Shoppinglist</div>
        } else if(this.props.actionToPerform === 'edit'){
            return <div>edit</div>
        } else{
            return <div>nothing to show</div>
        }
    }

   render() {
       return (
           this.showTitle()
       )
   }