javascript - react : Calling child component's method from parent component

标签 javascript reactjs react-native

我在 React Native 中有一个 ScrollView,它有很多 View 。我使用以下代码存储要查看的 ref

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

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

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()。

最佳答案

我在 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/

关于javascript - react : Calling child component's method from parent component,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34250702/

相关文章:

react-native - 无法让 Jest expo 应用程序与 react-navigation 一起使用

javascript - 隐藏元素以供稍后显示 - 浏览器如何更新屏幕?

javascript - 带有 ReactJS 和 Plyr 的 Vimeo API

javascript - 在 React 中使用 GET 请求中的数据并在子组件中使用

reactjs - 如何通过单击按钮将输入值从子组件获取到父组件?

javascript - React Native 中全局对象的模式

ios - react-native run-ios 不断失败

javascript - Angular 不清除文本输入

javascript - 在 Javascript 中实现快速排序

javascript - 此 JS 代码是否等待 AJAX 请求完成?