adi*_*eag 4 javascript react-native react-native-android
如何在react-native中调用其他组件的函数?
我有这个自定义组件,它在另一个地方呈现另一个组件和一个图像按钮.当点击图像时,我想从另一个组件调用一个函数.执行下面的示例时,我得到了undefined is not an object (evaluating this.otherComponent.doSomething')
export default class MainComponent extends Component {
_onPressButton() {
this.otherComponent.doSomething();
}
render() {
return (
<View style={styles.container}>
<TagContainer style={styles.flow_container} ref={(instance) => this.otherComponent = instance}>
</TagContainer>
<TouchableHighlight onPress={this._onPressButton}><Image source={require('./img/ic_add.png')} style={styles.add_tags_button_view} /></TouchableHighlight>
</View>
);
}
}
Run Code Online (Sandbox Code Playgroud)
和
export default class OtherComponent extends Component {
addTag() {
this.state.tags = this.state.tags.push("plm");
console.log('success..');
}
....
}
Run Code Online (Sandbox Code Playgroud)
Ado*_*zis 10
要使用功能组件执行此操作,您必须执行以下操作:
家长
useRef():const childRef = useRef()
// ...
return (
<ChildComponent ref={childRef} />
)
...
Run Code Online (Sandbox Code Playgroud)
孩子
ref构造函数:const ChildComponent = (props, ref) => {
// ...
}
Run Code Online (Sandbox Code Playgroud)
useImperativeHandle和forwardRef来自'react':import React, { useImperativeHandle, forwardRef } from 'react'
Run Code Online (Sandbox Code Playgroud)
useImperativeHandle将方法连接到ref对象。这些方法在内部不可用,因此您可能想使用它们来调用内部方法。
const ChildComponent = (props, ref) => {
//...
useImperativeHandle(ref, () => ({
// each key is connected to `ref` as a method name
// they can execute code directly, or call a local method
method1: () => { localMethod1() },
method2: () => { console.log("Remote method 2 executed") }
}))
//...
// These are local methods, they are not seen by `ref`,
const localMethod1 = () => {
console.log("Method 1 executed")
}
// ..
}
Run Code Online (Sandbox Code Playgroud)
forwardRef:const ChildComponent = (props, ref) => {
// ...
}
export default forwardRef(ChildComponent)
Run Code Online (Sandbox Code Playgroud)
子组件
import React, { useImperativeHandle, forwardRef } from 'react';
import { View } from 'react-native'
const ChildComponent = (props, ref) => {
useImperativeHandle(ref, () => ({
// methods connected to `ref`
sayHi: () => { sayHi() }
}))
// internal method
const sayHi = () => {
console.log("Hello")
}
return (
<View />
);
}
export default forwardRef(ChildComponent)
Run Code Online (Sandbox Code Playgroud)
父组件
import React, { useRef } from 'react';
import { Button, View } from 'react-native';
import ChildComponent from './components/ChildComponent';
const App = () => {
const childRef = useRef()
return (
<View>
<ChildComponent ref={childRef} />
<Button
onPress={() => {
childRef.current.sayHi()
}}
title="Execute Child Method"
/>
</View>
)
}
export default App
Run Code Online (Sandbox Code Playgroud)
Expo Snacks 上有一个交互式演示: https ://snack.expo.dev/@backupbrain/calling-functions-from-other-components
这个解释是根据这篇TutorialsPoint文章修改的
建议不要在组件之间直接通信,因为它会破坏封装.向组件发送道具并让它处理方法内部的更改是一种很好的做法componentWillReceiveProps.
class Main extends React.Component {
constructor(props) {
super(props);
this.state = { value: 0 };
this.handleClick = this.handleClick.bind(this);
}
handleClick(e) {
e.preventDefault();
this.setState({ value: ++this.state.value });
}
render() {
return (
<div>
<a href="#" onClick={this.handleClick}>click me</a>
<Child value={this.state.value}/>
</div>
);
}
}
class Child extends React.Component {
constructor(props) {
super(props);
this.state = { value: 0 };
}
componentWillReceiveProps(nextProps) {
if(nextProps.value !== this.state.value) {
this.setState({ value: nextProps.value });
}
}
render() {
return <div>{this.state.value}</div>
}
}
ReactDOM.render(<Main />, document.getElementById('app'));Run Code Online (Sandbox Code Playgroud)
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app"/>Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
12274 次 |
| 最近记录: |