reactjs - 在 React 中不向子组件传递值的道具
问题描述
我正在开发一个简单的食物应用程序。首先,它会在MenuComponent 和onClick中显示 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>
解决方案
所有组件都应该从 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>
);
}
}
推荐阅读
- ruby-on-rails - 答案中的 NoMethodError#new
- php - PHP 可执行 iptables
- r - 在 R 中一次重新定义多个时间序列
- gremlin - 用 project() 和 select() 在 Gremlin 中总结路径信息
- tensorflow - TensorFlow 导出具有多个 ckpt.data 文件的冻结图
- reactjs - 错误:找不到文件:“index.js”与磁盘上的相应名称不匹配:“./node_modules/React/react”
- apache - 重定向加载 http 而不是 https
- angularjs - 如何在初始化页面上加载 angularjs 自定义指令函数
- python-3.x - pyHook 和 pywin32 已安装但未找到
- excel - 如果单元格的文本中有特定单词,则突出显示该单元格