React.js 中子根数据传递简介
介绍
在 React.js 中设计和开发前端界面时,组件自然具有父子关系,数据将从父级流向子级。但是,某些用例可能需要违反惯例,将数据从子级向上传递到父级。在本指南中,您将在 React.js 中探索此用例。本指南假设您至少具有React.js 的中级知识和技能水平。
用例场景
假设您是基于微服务架构的 HR 项目的 React 开发人员。在您的应用程序结构中,主文件中有一个表,因此父组件也是如此。该表包含您的员工数据。您还有一个子表单组件,允许用户(在本例中为人力资源经理)插入新员工,这应该会更新父组件中的表。因此,您需要将用户数据发送回父组件。
环境设置
您将从创建一个新的 React 应用程序开始。在您的终端中,运行以下命令。npx create-react-app react-props使用您最喜欢的文本编辑器打开您的应用程序并导航到新创建的app.js文件。
从父组件向子组件传递 Prop
React 具有单向数据流。可以将其想象成一条从源头流向目的地的河流:河流只向一个方向流动。将数据从父组件传递到子组件时也是如此。您可以从下面的示例中查看。将app.js中的起始代码替换为下面的示例,并将文件名更改为ParentComponent.js。
      import React, {Component} from 'react';import ChildComponent from "./ChildComponent";
class ParentComponent extends Component {  constructor(props) {    super(props);    this.state = ({      value: "",    })   
 this.handleChange = this.handleChange.bind(this);  } 
 handleChange(e) {    let name = e.target.value    this.setState({      value: name  })}
render() {  return (      <div>        
<input type="text" name="name"   
 onChange={this.handleChange}  />        <ChildComponent fromParent={this.state.value}/>      </div>  );}}export default ParentComponent;
    
你的ChildComponent.js看起来应该是这样的:
      import React, {Component} from "react";
class ChildComponent extends Component{    constructor(props) { super(props);  }   
 render() { return ( <div>  <p>{this.props.fromParent}</p>   </div>  );  }}export default ChildComponent
    
将道具从孩子传递给父母。
如前所述,React 具有单向数据流。要将数据从子组件发送回父组件,您需要做一些额外的工作。返回到您的ChildComponent.js文件。在此示例中,您将把值从ChildComponent中的表单传递到ParentComponent表。
React 中的函数提供了一种简单的数据传递方式。每次 ChildComponent 中的输入字段发生变化时,此变化都会通过函数传播到ParentComponent。您的ChildComponent应如下所示:
      import React, {Component} from "react";
class ChildComponent extends Component{ 
   constructor(props) {  super(props) this.state =({  firstName: '', secondName:'',thirdName: ''})     
   this.handleFirstName = this.handleFirstName.bind(this)        
this.handleSecondName = this.handleSecondName.bind(this)      
  this.handleRole = this.handleRole.bind(this)       
 this.handleSave = this.handleSave.bind(this);    }   
handleFirstName(e) { let firstName = e.target.value  
this.setState({  firstName: firstName  }) }    handleSecondName(e) {  let secondName = e.target.value        this.setState({ secondName: secondName})    }    
handleRole(e) { let role = e.target.value        this.setState({ role: role  })    }    handleSave()
{ const { firstName, secondName, role} = this.state 
 this.props.handleInputChange(firstName, secondName, role)    }   
 render() {  return
 ( <div> <input type="text" name="firstName"  onChange=this.handleFirstName}/>  
              <input type="text" name="secondName" onChange={this.handleSecondName}/>
  <input type="text" name="role"  onChange={this.handleRole}/>  
    <button onClick={this.handleSave}>Save</button>  </div>   )}}export default ChildComponent
    
在构造函数中初始化字段,即firstName、secondName和role,它们将存储您的状态。接下来,您将编写函数来处理输入的变化并相应地设置状态。最后,您的按钮一旦被点击,将负责将您的表单数据发送回您的父组件,您将在父组件中更新您的表。这由 this.props.handleInputChange 处理,它将我们初始化的状态作为参数。您的ParentComponent应该如下所示:
      import React, {Component} from 'react';import ChildComponent from "./ChildComponent";
class ParentComponent extends Component {  constructor(props) {    super(props)   
 this.state =({          first_name: '',          second_name:'',          role: ''      })    
this.handleNewInput = this.handleNewInput.bind(this)  }  handleNewInput(firstName, secondName,role) {    this.setState({        first_name: firstName,        second_name: secondName,        role: role    })  } 
 render() 
{return ( <div> <table> <tbody>  <tr> 
<th>FirstName</th>  <th>LastName</th>      
               <th>Role</th>  </tr>   <tr> <td>{this.state.first_name}</td>  <td>{this.state.second_name}</td>                      
<td>{this.state.role}</td>  </tr>  </tbody></table>  <ChildComponent handleInputChange={this.handleNewInput}/>        </div>    )}}
export default ParentComponent
    
在上面的代码中,您创建了一个将显示新数据的表。您还初始化了状态以存储从子组件传递的数据。子组件在父组件中实例化,其值为“handleInputChange”,用于保存传递的数据。然后,您可以通过在表中调用this.state轻松检索数据。
结论
掌握了将数据从父组件传递到子组件并返回的技能后,您现在能够更好地在 React 组件内操作数据。React 和前端开发人员的工作大量需要这种技能。要进一步了解本指南,您可以在官方React.js 网站上了解有关 React 上下文的更多信息。
免责声明:本内容来源于第三方作者授权、网友推荐或互联网整理,旨在为广大用户提供学习与参考之用。所有文本和图片版权归原创网站或作者本人所有,其观点并不代表本站立场。如有任何版权侵犯或转载不当之情况,请与我们取得联系,我们将尽快进行相关处理与修改。感谢您的理解与支持!
                                
                                    
                                    
                                    
                                    
                                    
                                    
                                    
                                    
                                    
                                    
                                    
                                    
                                    
                                    
                                    
                                    
                                    
                                    
                                    
                                    
                                    
                                
                            
                                    
                                    
                                    
                                    
    
    
            
  
        
请先 登录后发表评论 ~