gpt4 book ai didi

React-Native - 从子方法调用父方法

转载 作者:行者123 更新时间:2023-12-04 04:39:55 24 4
gpt4 key购买 nike

我有一个子组件、父组件,我需要从子组件方法调用父组件方法。

代码

class Social extends Component {
constructor(props) {
super(props);

var tabLabel = this.props.tabLabel;

this.state = { text: 'Search ' + tabLabel + ' here...' , textInput: ''};
}
doneClick() {
this.props.showTrans;
var request = new XMLHttpRequest();
request.onreadystatechange = (e) => {
if (request.readyState !== 4) {
return;
}

if (request.status === 200) {
alert(request.responseText);
} else {
console.warn('error');
}
};

request.open('GET', "https://www.googleapis.com/youtube/v3/search?part=snippet&q=tupac&key=AIzaSyDFOz50C_XkuEh2T-2XTN9fqm_5xHYzbg8");
request.send();
}
render() {

return (
<View style={styles.menu} >


<View style={styles.searchbar} >
<Image style={{marginTop: 10 ,marginLeft: 10 , width: 20, height: 20}} source={require('./images/search.png')} />
<TextInput
onSubmitEditing={ this.doneClick }
style={{marginLeft: 5, color: '#757575', width: width - 80, height: 40, fontSize: 11,}}
onChangeText={(textInput) => this.setState({textInput})}
placeholder={this.state.text}
underlineColorAndroid="transparent"
/>
</View>
<View style={styles.sep} >
</View>

</View>

);
}
}

这是社交子组件

代码

class ScrollableTabBarView extends Component {

constructor(props) {
super(props);
this.showTrans = this.showTrans.bind(this);
this.state = { transWidth: 0,transHeight: 0,tabScroll: null };
alert('dddd');

}



hideTrans() {
this.setState({ transHeight: 0, transWidth: 0 });
}
showTrans() {
this.setState({ transHeight: width, transWidth: height });
}

render() {
return (<View style={{ width: width, height: height, position: 'absolute' }}>
<ScrollableTabView
style={{marginTop: 40, }}
initialPage={0}
renderTabBar={() => <ScrollableTabBar/ >}
>
<Text tabLabel='User'>My</Text>
<Social tabLabel='Settings'/>
<Social showTrans={ this.showTrans } hideTrans={ this.hideTrans } tabLabel='Youtube'></Social>
<Social tabLabel='Vimeo'>favorite</Social>
<Social tabLabel='MySpace'>project</Social>
</ScrollableTabView>

<View style={{ justifyContent: 'center', alignItems: 'center', top: 0, left: 0,width: this.state.transWidth, height: this.state.transHeight, position: 'absolute', backgroundColor:'rgba(52,52,52,0.5)' }}>
<Image style={{width: 30, height: 30}} source={require('./images/loader.gif')}/>

</View>

</View>)

}
}

父组件。

如何调用 this.props.showTrans

最佳答案

你几乎是在召唤它。应该是

doneClick = () => {
this.props.showTrans();
....
}

您可能仍然会收到错误消息,因为 showTrans 将在您的子组件范围内被调用。您可能希望将 showTrans、hideTrans 设置为如下所示的 ES2015 类属性,或者手动绑定(bind)它以便“此”范围是正确的。

hideTrans = () => {
this.setState({ transHeight: 0, transWidth: 0 });
}
showTrans = () => {
this.setState({ transHeight: width, transWidth: height });
}

关于React-Native - 从子方法调用父方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41382192/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com