【问题标题】:How to access other component props. (React)如何访问其他组件道具。 (反应)
【发布时间】:2019-08-04 10:41:31
【问题描述】:

认为我有一个组件:

    <Component1>
        <Component2 value={0}/>
        {window.console.log(Component2.value)}
    </Component1>

我该如何做这个 window.console.log 工作,因为我在尝试访问该道具时遇到问题。

【问题讨论】:

  • 我认为您应该阅读更多 react doc。这不是您应该从组件访问值的方式。如果您想记录该值,您应该将您的console.log 放入您的Component2
  • 您将把prop 即“0”从Component1 传递给Component2。您已经可以访问它了。
  • component2 的值在其中发生了变化,这只是一个图例。感谢您的帮助。

标签: javascript html reactjs jsx


【解决方案1】:

为什么不从component1 的状态访问该值?

class Component1 extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      counter: 0
    };
    this.incrementCounter = this.incrementCounter.bind(this);

  }


  incrementCounter() {
    this.setState(prevState => ({ counter: prevState.counter + 1 }));
  }



  render() {
    return (
      <View>
        <Component2
          incrementCounter={this.incrementCounter}
          counter={this.state.counter} />
        <Component3 counter={this.state.counter} />
      </View>
    )

  }
}

最后在 Component2 内部

<button onClick={this.props.incrementCounter}>
  click to increment counter
</button>

这是 React 的第一条规则,子组件不会改变数据 他们通过传递给他们的方法与父组件对话。这也使数据流更好,实际上这就是你应该使用 React 的方式。

【讨论】:

  • 因为它在component2内部发生了变化。
  • 状态中的值是响应式的,这意味着如果它在 Component2 中发生变化,它也会更新 Component3。所以这不是一个有效的论点
  • 我想你没看懂,我有第一个组件将状态传递给第二个组件,该状态是第二个组件的初始值。但是在第二个组件内部,这个值会发生变化,因为它是一个计数器,在第二个组件内部发生的所有过程之后,我必须读取它的响应,我需要读取 Component2 的新值。
【解决方案2】:

基本上你需要做的是传递给你的&lt;Component2&gt;一个回调函数作为prop,它返回更新到你的&lt;Component1&gt;的值(我做了一点StackBlitz => https://stackblitz.com/edit/react-rym9h9?file=Component2.js),在这里你有样品:

&lt;Component1&gt;:

import React, { Component } from 'react';
import { render } from 'react-dom';
import Component2 from './Component2';
import './style.css';

class Component1 extends Component {
  constructor() {
    super();
    this.state = {
      name: 'React'
    };
  }

  getUpdatedValue = (updatedValue) => {
    console.log('Here is your updated value: ', updatedValue);
  };

  render() {
    return (
      <div>
        <Component2 value={0} returnUpdatedValue={this.getUpdatedValue} />
        <p>
          Start editing to see some magic happen :)
        </p>
      </div>
    );
  }
}

render(<Component1 />, document.getElementById('root'));

&lt;Component2&gt;:

import React, { Component } from 'react';

class Component2 extends Component {
  componentDidMount() {
    const { value, returnUpdatedValue } = this.props;
    let updateValue = value + 100;


    returnUpdatedValue(updateValue)
  };

  render() {
    const { value } = this.props;

    return (
      <div>
      <h1>{value}</h1>
      </div>
    );
  }
}

export default Component2;

【讨论】:

    猜你喜欢
    • 2017-11-20
    • 1970-01-01
    • 1970-01-01
    • 2019-10-17
    • 1970-01-01
    • 1970-01-01
    • 2020-04-04
    • 1970-01-01
    • 2017-02-05
    相关资源
    最近更新 更多