[英]How to call child component function in React Native?
我想从兄弟组件中调用组件 function ,我决定使用父组件和参考来制作它。 这是我的父组件SMS-Registration.js
import React, {Component} from 'react';
import PhoneNumber from './Sms/PhoneNumber';
import VerificationCode from './Sms/VerificationCode';
class SmsRegistration extends Component {
state = {
confirm: false,
phone: '',
content: null,
};
setToTrue = () => {
this.setState({
confirm: true,
});
};
resendCode = () => {
this.child.testFunc();
};
render() {
return (
<>
{!this.state.confirm ? (
<PhoneNumber
onRef={ref => (this.child = ref)}
setToTrue={this.setToTrue}
/>
) : (
<VerificationCode
resend={this.resendCode}
/>
)}
</>
);
}
}
export default SmsRegistration;
第一个子组件PhoneNumber.js
import React, {Component} from 'react';
import {View} from 'react-native';
import {ButtonComponent} from 'components/common';
export default class PhoneNumber extends Component {
testFunc = () => {
console.log('test func click');
};
setToTrue = () => {
this.props.setToTrue();
};
render() {
return (
<View>
// this is custom button component which receives 2 params (title, callback)
<ButtonComponent
buttonCaption="Set to True"
onTouch={this.setToTrue}
/>
</View>
);
}
}
和第二个子组件Verification.js
import React, {Component} from 'react';
import {View} from 'react-native';
import {ButtonComponent} from 'components/common';
export default class VerificationCode extends Component {
constructor(props) {
super(props);
}
resendCode = () => {
this.props.resend();
};
render() {
const changeValue = (value) => {
this.getData(value);
};
return (
<View>
<ButtonComponent
buttonCaption="Resend Code"
onTouch={this.resendCode}
/>
</View>
);
}
}
当我尝试从PhoneNumber.js运行方法时,它说 this.child 是未定义的。 请帮我解决这个问题。
我认为这是因为 PhoneNumber 组件尚未初始化。 由于您有条件确认 state PhoneNumber 组件和 this.child 在它变为真之前不会被初始化。 这就是您收到未定义错误的原因。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.