在下面的代码中,有人可以建议如何访问传递给子QRScan组件的closeModal prop中存储的函数吗?
我尝试过在QRScan的构造函数中使用this.props.closeModal.bind(this),但是当我在_onBarCodeRead函数中调用this.props.closeModal()时,我得到了一个undefined is not an object (evaluating 'this.props.closedModal')错误。
道具肯定会被传递给构造函数,我只是看起来不能正确地绑定函数。任何帮助都非常感谢!
class Test extends React.Component {
constructor(props) {
super(props);
}
_test(){
console.log("test worked")
}
render() {
return (
<View>
<QRScan closeModal={this._test}/>
</View>
}
}子类:
class QRScan extends React.Component {
constructor(props)
{
super(props)
console.log(this.props)
this.props.closeModal.bind(this);
}
render() {
return (
<BarcodeScanner
onBarCodeRead={this._onBarCodeRead}
width={windowWidth}
height={windowWidth * cameraAspectRatio}
style={styles.camera}>
<View style={styles.rectangleContainer}>
<View style={styles.rectangle} />
</View>
</BarcodeScanner>
);
}
_onBarCodeRead(e) {
console.log(e);
Vibration.vibrate();
this.props.closeModal();
}
}发布于 2016-09-23 14:54:12
问题实际上是this._onBarCodeRead没有正确绑定。
在子组件的构造函数中,您需要添加以下this._onBarCodeRead = this._onBarCodeRead.bind(this);
发布于 2016-09-23 05:09:46
绑定函数不会就地修改函数。相反,它返回结果函数,您可以将该函数赋值给变量。
所以从理论上讲,你可以做this.props.closeModal = this.props.closeModal.bind(this);,但这对react不起作用。因此,我建议在类上创建一个方法,绑定它,并从那里访问属性。例如:
class QRScan extends React.Component {
constructor(props)
{
super(props)
this.closeModal = this.closeModal.bind(this)
}
closeModal() {
this.props.closeModal.call(this);
}
}当然,通常推荐的一种做法是建议将this放在类中,而不是将其传递给props方法。
为了让你的代码正常工作,我想你必须对你的this._onBarCodeRead方法做同样的绑定。
https://stackoverflow.com/questions/39648753
复制相似问题