紅顏莎娜
2022-11-11 16:19:33
Child.js:export default class Child extends Component { testFunc = () => { console.log("test") } componentDidMount() { this.props.onRef(this) }父.js:export default class Parent extends Component { render() { return ( <> <Child onRef = {ref => (this.child=ref)}> </Child> <Button onPress={this.child.testFunc()}></Button> </> ) }}我想知道如何從 React Native 的父組件調(diào)用子組件中的函數(shù)?我嘗試了上面的代碼,我收到錯誤“TypeError undefined is not an object (evaluate '_this.child.testFunc')。當(dāng)我在這里嘗試建議的解決方案時遇到同樣的錯誤:Call child function from parent component in React Native。有人可以幫我嗎?
2 回答

人到中年有點(diǎn)甜
TA貢獻(xiàn)1895條經(jīng)驗(yàn) 獲得超7個贊
在我看來,這是一個糟糕的設(shè)計。如果您希望testFunc()
在父組件中可用,那么您應(yīng)該在父組件中定義該函數(shù)。
為了在子組件中使用此功能,您可以將此功能傳遞給道具中的子組件。
從 ParentComponent.js 你可以像這樣傳遞這個函數(shù)
<ChildComponent func = {testFunc} />
在 ChildComponent.js 中,您可以像這樣回調(diào)此函數(shù) this.props.func()

當(dāng)年話下
TA貢獻(xiàn)1890條經(jīng)驗(yàn) 獲得超9個贊
請試試這個。由于 javascript 語法,在調(diào)用 testFunc 時刪除括號。
export default class Parent extends Component {
render() {
return (
<>
<Child onRef = {ref => (this.child=ref)}> </Child>
<Button onPress={this.child.testFunc}></Button>
</>
)
}
}
添加回答
舉報
0/150
提交
取消