【发布时间】:2019-10-12 21:35:14
【问题描述】:
我已将自定义 component 导入我的 screen 并在 render() 函数中呈现它。然后,为该自定义组件创建了一个ref。现在,render() 函数看起来就像这样。
render() {
return (
<View>
<MyComponent ref={component => this.myComponent1 = component} />
<MyComponent ref={component => this.myComponent2 = component} />
<MyComponent ref={component => this.myComponent3 = component} />
</View>
)
}
然后,在同一个screen 文件中,我创建了另一个函数来访问我的自定义组件的状态。我是这样写的。
myFunction = (ref) => {
ref.setState({ myState: myValue })
}
然后,我想像这样分别为这些单独的组件调用该函数。 (在screen 文件中)
this.myFunction(this.myComponent1)
this.myFunction(this.myComponent2)
this.myFunction(this.myComponent3)
但是,它不起作用。它给了我以下错误。
null is not an object (evaluating 'ref.setState')
其实我需要这个myFunction做的是,
this.myComponent1.setState({ myState: myValue })
this.myComponent2.setState({ myState: myValue })
this.myComponent3.setState({ myState: myValue })
状态myState 位于component 中,而我想通过screen 文件中的myFunction() 访问它。
你能帮我解决这个问题吗?
【问题讨论】:
标签: javascript react-native ref