【问题标题】:react: Calling child component's method from parent componentreact: 从父组件调用子组件的方法
【发布时间】:2015-12-13 11:42:36
【问题描述】:

我在 react native 中有一个 ScrollView,它有很多视图。我使用以下代码存储要查看的参考

cards.push(
  <Card
    ref={(ref) => {
      console.log(ref);
      this.cardRef[index] = ref;
      ref.testMethod();
    }} />
);

卡片是一个单独的组件,如下所示:

class Card extends Component {
  constructor(props) {
    super(props);

    this.testMethod = this.testMethod.bind(this);
  }

  testMethod() {
    console.log('this.is.test.method');
  }

  render() {
    return (
      <View style={styles.container}>
        <Text>This.is.a.card</Text>
      </View>
    )
  }
}

但是它说 testMethod 是未定义的,不能调用 ref.testMethod()。

【问题讨论】:

    标签: javascript reactjs react-native


    【解决方案1】:

    我在 jsfiddle 上玩过你的代码,看起来好像调用了子方法:

    var Card = React.createClass({
      testMethod() {
        console.log('this.is.test.method');
      },
      render() {
        return (
          <h1>this is a card.</h1>
        )
      }
    });
    
    var Parent = React.createClass({
        render: function() {
            return <div><Card ref={(r) => {r.testMethod()}}/></div>;
        }
    });
    
    ReactDOM.render(
        <Parent />,
        document.getElementById('container')
    );
    

    https://jsfiddle.net/vq110d69/

    【讨论】:

    • 在 rnplay 上尝试使用示例项目时,代码也对我有用:rnplay.org/apps/tAeu6g。但不在我当前的应用程序中。将不得不自己检查问题。感谢您的回复。
    猜你喜欢
    • 2016-12-03
    • 2018-07-20
    • 1970-01-01
    • 1970-01-01
    • 2021-05-02
    • 2022-07-07
    • 2023-01-08
    • 2017-11-24
    相关资源
    最近更新 更多