【问题标题】:How to pass value to props from component and set state如何将值从组件传递给道具并设置状态
【发布时间】:2021-01-07 21:06:21
【问题描述】:

我是 react 新手,尝试将值从父组件传递到子组件到 props 并将值存储在状态中。但它甚至不调用 console.log 语句

这是我通过单击按钮更改字符串的功能

let actionToPerform = "";

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

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

<Edit action={actionToPerform}
                    />

子组件

从“反应”导入反应; 从 './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。

【问题讨论】:

    标签: reactjs components react-props react-state


    【解决方案1】:

    您正在将 action 道具传递给孩子,但正在解析 actionToPerform。您需要在子级中解析 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
       )
      }
      }
    

    【讨论】:

    • 像魅力一样工作。现在只需弄清楚为什么 在不点击按钮的情况下触发该功能
    • 创建一个问题并告诉我。乐于助人
    猜你喜欢
    • 2017-09-23
    • 1970-01-01
    • 2020-10-08
    • 2018-08-13
    • 2019-11-16
    • 1970-01-01
    • 2018-08-25
    • 2020-11-06
    • 1970-01-01
    相关资源
    最近更新 更多