反应 | 将数据从父组件传递给子组件

Sel*_*vin 4 reactjs react-props

在 React 中,我有类似的文件

--parent.js
--child.js
--App.js
Run Code Online (Sandbox Code Playgroud)

parent.js包含文本框和按钮

child.js包含 P 标签

App.js包含父组件和子组件

问题

在按钮单击时将来自父级的文本框值传递给子级并在子段落标记中显示该值。

完整代码 堆栈闪电战

G_S*_*G_S 5

更新了您的示例以将数据传递给子组件。

https://stackblitz.com/edit/react-trmj9i?file=child.js

在下面添加代码以供快速参考

索引.js

import React, { Component } from 'react';
import { render } from 'react-dom';
import Parent from './parent';
import Child from './child';
import './style.css';

class App extends Component {
  constructor() {
    super();
    this.state = {
      name: 'React',
      parentTextBoxValue: ''
    };
  }
  handleParentData = (e) => {
this.setState({parentTextBoxValue: e})
  }

  render() {
    return (
      <div>
        <Parent handleData={this.handleParentData} />
        <Child parentTextBoxValue={this.state.parentTextBoxValue}/>
      </div>
    );
  }
}

render(<App />, document.getElementById('root'));
Run Code Online (Sandbox Code Playgroud)

父.js

import React, { Component } from 'react';
import Button from 'react-uikit-button';

class Parent extends Component {

constructor(props){
    super(props);
    this.state={TextBoxValue: ""}
}   

  SubmitValue = (e) => {
     this.props.handleData(this.state.TextBoxValue)
  }

   onChange=(e)=>{
this.setState({TextBoxValue: e.target.value})
   } 
  render() {
    return (
      <div className="">
        <input type="text" name="TextBox"  onChange={this.onChange}
         />
        <Button onClick={this.SubmitValue}>Submit Value</Button>
      </div>
    );
  }
}

export default Parent;
Run Code Online (Sandbox Code Playgroud)

孩子.js

import React, { Component } from 'react';

class Child extends Component {

    constructor(props){
        super(props);
    }


  render() {
    return (
      <div className="App">
       <p>{this.props.parentTextBoxValue}</p>
      </div>
    );
  }
}

export default Child;
Run Code Online (Sandbox Code Playgroud)

只是为了给出我所做的,将一个函数从 App.js 传递给父级,这可以帮助提升状态。在父组件中处理文本框的 onchange 和提交更新的应用程序状态。最后将此状态传递给子组件。


小智 5

import React from "react";

class Parent extends React.Component(){
    constructor(props){
        super(props);
        this.state={
            name:"suraj"
        }
    }

    render(){
        return(
            <div className = "parent">
                <child data={this.state.name}/> 
            </div>
        );
    }

}

export default Parent;

export function Child(props){
    return(
        <div>{props.data}</div>
    );
}
Run Code Online (Sandbox Code Playgroud)