[英]React Native: When accessing a component via ref, how do you access methods of that component?
[英]How to access ref of a component through a function in React Native?
我已經將一個自定義component
導入到screen
,並在render()
函數中對其進行了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 })
當我想通過screen
文件中的myFunction()
訪問它時, component
的狀態為myState
。
您能幫我解決這個問題嗎?
這不是從父組件設置子組件的setState的好習慣。 我假設您想通過嘗試這種方法為子組件的狀態設置一些值。
您可以將這些值保留在本地狀態,然后將其傳遞給道具,子組件將在那里重新渲染/獲取更新的值。
class Component {
constructor() {
this.state = {
myValues: {
component1: "abc",
component2: "xyz",
component3: "123",
}
}
}
myFunction(componentName, newValue) {
this.setState({
myValues: {
...this.state.myValues,
[componentName]: newValue
}
})
}
render() {
return (
<View>
<MyComponent value={this.state.myValues.component1} />
<MyComponent value={this.state.myValues.component2} />
<MyComponent value={this.state.myValues.component3} />
</View>
)
}
};
首先確保MyComponent是一個組件,而不是一個無狀態組件,然后要更改狀態,請嘗試以下操作:
myFunction = (ref) => {
ref.current.setState({ myState: myValue }
}
當然,要使其正常工作,您的組件必須已經掛載,如果嘗試例如在構造函數中調用它,則它將無法工作
在組件內部,在componentDidMount函數中,請添加
componentDidMount() {
this.props.refs(this)
}
setState(key, value){
this.setState({[key]:value})
}
並將ref參數更改為refs
<MyComponent refs={component => this.myComponent1 = component} />
myFunction = (ref) => {
ref.setState('myState', 'myValue')
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.