【问题标题】:How to pass child properties/values to parent component when screen is loaded加载屏幕时如何将子属性/值传递给父组件
【发布时间】:2019-07-12 09:01:32
【问题描述】:

如何在加载 react 应用程序时将属性值从子组件发送到父组件?我有一个名为 app.js 的父组件,它呈现一个包含 JSON 组件的主组件。 加载反应应用程序时,我的属性 JSONValue(在 app.js 中定义)包含一个空字符串。当加载反应应用程序时,父组件中的 JSONValue 应该包含子 JSON 组件中已经定义的值。如何在初始渲染时将这些值从 JSON 组件发送到 APP 组件?

我现在可以做到这一点的唯一方法是更改​​ react 应用程序中的值 --> json 组件。然后它将值从孩子发送给父母。

所以: JSONValue 的值是在 JSON 组件中定义的,只有在 JSON 组件发生变化时才会应用到 app.js 中的 JSONValue。这应该在 react 应用加载后立即应用。

APP.JS:

import React, { Component } from 'react';
import Home from './Components/Home';
import './App.css';


class App extends Component 
{
  constructor(props) {
    super(props);
    this.state = {

      JSONValues: {
        JSONValue: ""
      }
    }

    this.changeJSON = this.changeJSON.bind(this);



changeJSON(e, JSONId)
{
  const elem = e.target;
  const JSONValue = elem.value;

  let tmpJSONValues = this.state.JSONValues;
  tmpJSONValues[JSONId] = JSONValue;

  this.setState(prevState => ({
    JSONValues: tmpJSONValues
  }));
}

  render() {
    return (
        <div>
          <Home 
            JSONValues={this.state.JSONValues}
            changeJSON={this.changeJSON}
          />
        </div>
    )
  }
}

export default App;

主页.JS: 返回:

<div>
  <JSON
    JSONValues={props.JSONValues} 
    changeJSON={props.changeJSON}
   />
</div>

JSON.JS:


    import React, { Component } from 'react';

    export default class JSON extends Component {
        render() {
            let JSONValue = "";

            if(this.props.JSONValues){
                JSONValue = this.props.JSONValues.JSONValue;
            }

            JSONValue = 'value';

            return (
                <div>
                    <textarea className="json" spellCheck={false}  value={JSONValue}  onChange={(e) =>this.props.changeJSON(e, 'JSONValue')}>

                    </textarea>
                </div>
            )
        }
    }

【问题讨论】:

    标签: javascript reactjs


    【解决方案1】:

    通常,你在父组件中创建状态,然后通过 props 将数据传递给子组件。

    在父组件中,你还创建了一个changeStateHandler,你也通过props传递给子组件。

    当孩子需要更新其状态时,它使用传入的changeStateHandler。然后父级更新其状态并通过道具将新状态传递回子级。孩子在获得新道具时重新渲染。

    这是一个简单的人为示例:

    Demo.js

    import React, {useState} from 'react';
    
    export const Parent = () => {
        const [counter, setCounter] = useState(0);
        return (
          <div>
              <div>Parent says the count is now: {counter}</div>
              <Child counter={counter} handleCounter={setCounter} />
          </div>
        );
    };
    
    const Child = ({counter, handleCounter}) => {
        const incrementCounter = () => handleCounter(counter++); 
        const decrementCounter = () => handleCounter(counter--);
        return (
            <div>
                <button onClick={incrementCounter}>+</button>
                <button onClick={decrementCounter}>-</button>
            </div>
        );
    };
    

    【讨论】:

      【解决方案2】:

      通过子道具传递一个函数来设置挂载时的父状态,如下所示:

      class Child extends React.Component {
        componentDidMount(){
          const jsonString = '{"foo":"bar"}';
          this.props.onMount(jsonString)
        }
        
        render() {
          return null;
        }
      }
      
      
      class App extends React.Component {
        state = {
          jsonData: null
        }
        
        setJson = jsonData => this.setState({ jsonData });
        
        render(){
          return (
            <div>
              <span>parent's state jsonData:</span>
              <pre>{this.state.jsonData}</pre>
              <Child onMount={this.setJson} />
            </div>
          )
        }
      }
      
      ReactDOM.render(<App/>, document.getElementById('root'))
      <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
      <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
      <div id="root"></div>

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-02-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-03-17
        • 1970-01-01
        • 2021-09-20
        • 1970-01-01
        相关资源
        最近更新 更多