如何在Native React中的孩子内部调用父功能
问题描述:
经过数小时的搜索后才发现没有找到答案......我在寻求您的帮助。如何在Native React中的孩子内部调用父功能
所以我想要做的是:在子内调用名为_toggleSearchBar()的函数(它在父类中),这样当onPress事件(在子项中)触发它时,会更改“isVisible”家长。
家长
class HomeScreen extends React.Component {
constructor(props) {
super(props);
this.state = {isVisible: false};
}
static navigationOptions = {
title: 'P O S T E R',
headerStyle: { backgroundColor: '#CECECE' },
headerTitleStyle: { color: 'black', fontSize: 30, fontFamily: 'HelveticaNeue-CondensedBlack'},
headerRight: <DisplayIcon src={require('./ressources/icon_search.png')} myMethod={'HERE'}/>,
headerLeft: <DisplayIcon src={require('./ressources/icon_aroundMe.png')}/>,
};
render() {
const { navigate } = this.props.navigation;
return (
<View>
<View style={styles.bck}>
<ScrollView>
<DisplayImage src={require('./ressources/logo.jpg')} />
<DisplayImage src={require('./ressources/logo1.jpeg')} />
<DisplayImage src={require('./ressources/logo2.jpg')} />
<DisplayImage src={require('./ressources/logo3.jpeg')} />
<DisplayImage src={require('./ressources/logo4.jpg')} />
<DisplayImage src={require('./ressources/logo5.jpeg')} />
<DisplayImage src={require('./ressources/bde.jpeg')} />
</ScrollView>
</View>
<Display enable={this.state.isVisible} style={styles.ViewIn}>
<View>
<TextInput style={styles.textIn}></TextInput>
</View>
</Display>
</View>
)
}
_toggleSearchBar() {
this.setState(previousState => {
return { isVisible: !this.state.isVisible };
});
}
}
儿童
class DisplayIcon extends React.Component {
constructor(props) {
super(props);
}
render() {
return (
<TouchableHighlight onPress={this.myMethod} activeOpacity= {0.4} underlayColor={ 'rgb(206, 206, 206)' }>
<Image style={styles.Picture} source={this.props.src}/>
</TouchableHighlight>
);
}
}
const styles = StyleSheet.create({
Picture: {
marginLeft: 10,
marginRight: 10,
height: 30,
width: 30,
}
});
绑定没有工作。不通过道具传递功能...
感谢您的帮助和您的时间!
答
在子组件你应该调用this.props.myMethod
而不是this.myMethod
。
例子:
<TouchableHighlight onPress={this.props.myMethod} activeOpacity= {0.4} underlayColor={ 'rgb(206, 206, 206)' }>
在你家长你应该通过在道具的孩子 - myMethod={this._toggleSearchBar}
。
例子:
<DisplayIcon src={require('./ressources/icon_search.png')} myMethod={this._toggleSearchBar}/>
请注意,您应该绑定_toggleSearchBar
到class
。
做它在constructor
:
constructor(props){
super(props);
this._toggleSearchBar = this._toggleSearchBar.bind(this);
}
答
HELP对于修真
子里面。
这不是工作(通过父函数)
<TouchableHighlight onPress={this.props.myMethod} activeOpacity= {0.4} underlayColor={ 'rgb(206, 206, 206)' } style={styles.lol}>
<Image style={styles.Picture} source={this.props.src}/>
</TouchableHighlight>
这是工作(通过子功能)
lol() {
alert('lol');
}
render() {
return (
<TouchableHighlight onPress={this.lol} activeOpacity= {0.4} underlayColor={ 'rgb(206, 206, 206)' } style={styles.lol}>
<Image style={styles.Picture} source={this.props.src}/>
</TouchableHighlight>
请不要发布图片的代码。直接将您的代码添加到问题中,以便帮助人们帮助您。 – bennygenel
好吧,我的坏 – Maxime
位于层次结构中的DisplayIcon组件在哪里?因为我在HomeScreen中看到的只是DisplayImage。 DisplayImage和DisplayIcon是否是相同的组件? –