reactjs - react |将数据从父组件传递给子组件

标签 reactjs react-props

在 React 中,我有类似的文件

--parent.js
--child.js
--App.js

parent.js 包含文本框和按钮

child.js包含P标签

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

问题

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

完整代码 stackblitz

最佳答案

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

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

添加下面的代码以供快速引用

index.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'));

parent.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;

child.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;

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

关于reactjs - react |将数据从父组件传递给子组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48952882/

相关文章:

javascript - 在 react 中的 url 更改上重新呈现相同的组件

javascript - setState 也会改变屏幕 Prop

reactjs - 画面 react : Embeded Tableau sheet won't update on url change

javascript - 在 Redux/React 中设置/清除输入

ReactJS 事件 - this.props.onSubmit(this.state....)

javascript - 如何传递父组件的状态以在子组件中使用?

javascript - 为什么在以下场景中 AJAX 之后需要使用 ReactJS 状态来更新 UI

javascript - 警告 : Failed prop type: Invalid prop `children` of type `string` supplied to `Dropzone` , 应为 `function`

node.js - 参数错误必须是 react 元素,但您传递了未定义

reactjs - 为什么我们在子组件中使用时要在大括号中编写 props