首页 > 解决方案 > 在 React 中不向子组件传递值的道具

问题描述

我正在开发一个简单的食物应用程序。首先,它会在MenuComponentonClick中显示 discDetails,它会将所选菜肴的Id传递给名为 getDish(dishdetail)的函数 这里我想向我的CartComponent发送道具或状态,它将显示所选菜肴的详细信息。

问题 1道具没有传递给购物车(未定义的值),但是如果我在MenuComponent 中执行 console.log,则会显示菜肴详细名称、id

我如何将道具/状态传递给购物车请指导我。

//Here im binding my function

    class Menu extends Component {
  constructor(props) {
    super(props);
    this.getDish = this.getDish.bind(this);
  }




//This is my getDish function(in which i want to send props to Cart)
    getDish(dishDetail) {
        return (
          <React.Fragment>
            
            <Cart dishdetail={dishDetail}/>  **//undefined in Cart**
            {console.log({dishDetail.name})} **//it is working perfectly**
          </React.Fragment>
        );
      }

工作正常

从我发送数据的地方 onClick 功能

<button
    onClick={() => this.getDish(this.props.dishes[index])}
  ></button>

标签: reactjsundefinedreact-propssetstate

解决方案


所有组件都应该从 render 方法渲染。并且可以使用状态来控制行为。

// 类菜单

constructor(props) {
        super(props);
        this.state = {
            dishDetail: null
        };
        this.getDish = this.getDish.bind(this);
    }

    getDish(selectedDish) {
        this.setState({
            dishDetail: selectedDish
        });
    }

    render() {
        return (
            <>
                <button onClick={() => this.getDish(this.props.dishes[index]])}>Click Me</button>
                {/*Cart is called from render and value passed from state*/}
                <Cart dishdetail={this.state.dishDetail}/> 
            </>
        );
    }

您的购物车类将使用您的新数据重新呈现

class Cart extends React.Component {
    constructor(props) {
        super(props);

    }

    render() {
        console.log('cart', this.props);
        return (
          <div>You added {this.props.dishdetail} to cart</div>
        );
    }
}

推荐阅读