如何将值从组件传递给道具并设置状态

How to pass value to props from component and set state

我是 React 的新手,我尝试将一个值从父组件传递到子组件再到道具并将该值存储在状态中。但它甚至没有调用 console.log 语句

这是我通过点击按钮改变字符串的函数

let actionToPerform = "";

function changeEdit(){
    if(actionToPerform === 'edit'){
        actionToPerform = 'new'
    }else{
        actionToPerform = 'edit'
    }
}

在父组件中,在渲染中我有这个:

<Edit action={actionToPerform}
                    />

子组件

从 'react' 导入 React; 从 './edit.module.css';

导入 * 作为样式
export default class Edit extends React.Component {

    constructor(props){
        super(props);
        this.state = {actionToPerform: this.props.actionToPerform}
        console.log("props:" + props)
        console.log("parsed state: " + this.state)
    }

    showContent = ()=>{
        if(this.state.actionToPerform == "edit"){
            return <div>Shoppinliste bearbeiten</div>
        }
    }

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

我的目标是,根据通过单击按钮更改的状态来显示 div 或不显示。

您正在将 action 道具传递给 child,但正在解析 actionToPerform。您需要在 child.

中解析 action

控制台日志应该在构造函数之外。

export default class Edit extends React.Component {

constructor(props){
    super(props);
    this.state = {actionToPerform: this.props.action}
   
}



showContent = ()=>{
    console.log("props:" + props)
    console.log("parsed state: " + this.state)

    if(this.state.actionToPerform == "edit"){
        return <div>Shoppinliste bearbeiten</div>
    }
}

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