【问题标题】:Initializing state of a component from another component and get the state value从另一个组件初始化一个组件的状态并获取状态值
【发布时间】:2018-09-28 20:16:44
【问题描述】:

我是异步机制的 reactnative/js 世界的新手,我阅读了很多类似的示例,但我不清楚。所以请在这里找到我的问题。

我正在尝试创建一个组件(在示例中称为“锚”)并从另一个组件更新其状态(名称参数)。 我想从父组件中获取“锚”组件的属性 state.name 值。 我的问题如下: - 锚组件的创建似乎没有处理组件创建的 props.name 参数 - 不知道如何从父组件(示例中的App)访问组件状态参数值(his.state.name)

https://jsfiddle.net/n5u2wwjg/203556/

锚组件

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

 /*
    getName(){
       return this.state.name;
    }
 */  
}  

以及 App 组件:

class App extends React.Component <any> {
  constructor(props) {
    super(props)
    this.state = {
       anchor : undefined,
       items: [
           { text: "Learn JavaScript", done: false },
           { text: "Learn React", done: false },
           { text: "Play around in JSFiddle", done: true },
           { text: "Build something awesome", done: true }
       ]
     }
 }

addAnchor(){
    var anchor = new Anchor('hello');
    this.setState({
        anchor : anchor,
    });
    console.debug('get my anchor name: '+ this.state.anchor.name);
}

render() {
    return (
        <div>
            <h2>Todos:</h2>
                {this.state.anchor.name}
            <ol>
                {this.state.items.map(item => (
                <li key={item.id}>
                <label>
                    <input type="checkbox" disabled readOnly checked={item.done} /> 
                    <span className={item.done ? "done" : ""}>{item.text}</span>
                </label>
                </li>
                ))}
            </ol>
        </div>
    )}
}

【问题讨论】:

  • 不要用 props 初始化 state。
  • 我也尝试使用其他函数来更新状态(调用 SetState),但它不起作用。
  • 将父状态作为道具传递......然后传递另一个道具......一个函数。这是一个例子.....&lt;Anchor name={this.state.name} changeName={newName =&gt; this.setState({name: newName})} /&gt; inside anchor 像这样使用 thise....this.props.name 访问名称,this.props.changeName("example") 将名称更改为示例

标签: reactjs react-native


【解决方案1】:

如果您想像一些简单的 POJO 一样操作组件

那么试试这个:

class Anchor extends React.Component {
  render() {
    return (
      <div>
        <h3>Name: {this.props.name}</h3>
      </div>
    );
  }
}

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      name: 'Hello',
      items: [
        { text: 'Learn JavaScript', done: false },
        { text: 'Learn React', done: false },
        { text: 'Play around in JSFiddle', done: true },
        { text: 'Build something awesome', done: true }
      ]
    };
  }
  addAnchor(){
     const anchor = React.createElement('Anchor', { name: this.state.name }, '');
     console.log(anchor.props.name);
  }

  render() {
    return (
      <div>
        <h2>Todos:</h2>
        <Anchor name={this.state.name} />
        <ol>
          {this.state.items.map(item => (
            <li key={item.id}>
              <label>
                <input type="checkbox" disabled readOnly checked={item.done} />
                <span className={item.done ? 'done' : ''}>{item.text}</span>
              </label>
            </li>
          ))}
        </ol>
      </div>
    );
  }
}
ReactDOM.render(<App />, document.querySelector("#app"))

我们必须以 React 的方式实例化一个 React 组件:

React.createElement('Anchor', { name: this.state.name }, ''); // <~~ like this

//var anchor = new Anchor('hello'); <~~ not like this

更多详情,您可以在这里阅读:React Without JSX

希望对您有所帮助!

【讨论】:

  • 我会试一试的。在我的项目中,我有一些不需要任何渲染或 HTML 表示的特定算法。事实上,为此我想像一些简单的 POJO 一样操作组件。有没有办法在渲染之外做到这一点?
  • thks 但 createElement 将创建一个与我的 Anchor 组件无关的对象元素。使用此解决方案,我无法从原始 Anchor 组件中调用某些方法,例如: anchor.getName() ?
  • 哦,我明白了!那你为什么不直接创建一个普通的 Javascript 类呢?
  • 您指出了正确的解决方案!我不确定是否将简单的 Javascript 类与 React Native 一起使用,因为没有关于此的文档(我假设只有组件......)。很好用!
猜你喜欢
  • 2019-06-22
  • 2021-02-05
  • 2019-12-11
  • 2020-07-01
  • 1970-01-01
  • 2021-10-18
  • 1970-01-01
  • 2016-10-14
  • 2021-01-11
相关资源
最近更新 更多