如何在 react.js 中将数据从父级传递给子级 [英] How to pass data from parent to child in react.js
问题描述
我有一个父组件,它有 1 个子组件.我正在通过道具传递数据来更新我的孩子.最初,它工作正常,但是当我单击按钮并使用 setState 更新状态时,在 setState 完成时,子项将使用旧值呈现.我已经在孩子中使用 componentWillReceiveProps 解决了它,但这是正确的方法吗?
在下面的代码中,如果我在 filterResults 函数中执行 setState,它不会更新 Emplist 组件.
import React, { Component } from 'react';从 './search-bar' 导入 {Search}从'./emplist'导入Emplist类 App 扩展组件 {构造函数(道具){超级(道具);this.emp=[{name:'pawan',年龄:12},{name:'manish',年龄 : 11}]this.state={emp:this.emp};this.filterResults=this.filterResults.bind(this);}过滤结果(val){如果(这个状态){让过滤=[];过滤推(this.emp.find(e=>{返回 e.age==val}));this.setState({emp:filt});}}使成为() {返回 (<div className="应用程序"><搜索过滤结果={this.filterResults}/><Emplist emp={this.state.emp}/>
);}}导出默认应用;
EmpList 组件从反应"导入反应,{组件}导出默认类 Emp 扩展组件{构造函数(道具){超级(道具);this.emplist=this.props.emp.map(e=>{return {e.name} });this.next=this.emplist;}componentWillReceiveProps(nextProps,nextState,prevProps,prevState,nextContext,prevContext){//this.props.updated(this.props.empo);this.next=nextProps.emp[0];如果(这个.下一个)this.emplist= nextProps.emp.map(e=>{return {e.name} });}使成为(){如果(!this.next)返回 未找到名称别的返回 (<div><br/><p>列表在这里</p><ul>{this.emplist}
)}}
如果你想从父级传递给子级,你可以使用 props 传递,如果你想做反向,你可以将一个函数从父级传递给子级和而不是使用此传递的函数将某些内容发送回父级.
孩子看起来像这样
class Reciepe 扩展组件{使成为(){const { 标题、图片、说明 } = this.props;const成分=this.props.ingredients.map((ing,index)=>(<li key={index} >{ing}</li>));返回 (<div className='recipe-card'><div className='recipe-card-img'><img src={img} alt={title}/>
<div className='recipe-card-content'><h3 className='recipe-title'>食谱{title}</h3><ul>{成分} </ul><h4>说明:</h4><p>{指令}</p>