[英]How to call a function in one React component by button click in another component
[英]How to call function from one component to another component with Button
我在一個名為formSignup.js
組件中創建了一個Submit()
函數,並創建了另一個名為buttonSubmit.js
組件,其中包含帶有該按鈕的 Button(onPress) 我想調用位於ormSignup.js
Submit()
函數。
為提交按鈕創建單獨組件的原因是,我為動畫編寫了很多代碼,而且我想在loginComponent.js
重用該按鈕。
表單注冊.js
submit = () => {
...
}
按鈕提交.js
How can i call submit function from fromSignup.js here
_onPress() {
if (this.state.isLoading ) return;
this.setState({isLoading: true});
Animated.timing(this.buttonAnimated, {
toValue: 1,
duration: 200,
easing: Easing.linear,
}).start();
setTimeout(() => {
this._onGrow();
}, 2000);
setTimeout(() => {
Actions.mainScreen();
this.setState({isLoading: false});
this.buttonAnimated.setValue(0);
this.growAnimated.setValue(0);
}, 2300);
}
-----
return(
<TouchableOpacity
onPress={this._onPress}
activeOpacity={1}>
{this.state.isLoading ? (
<Image source={spinner} style={styles.image} />
) : (
<Text style={styles.text}>Go</Text>
)}
</TouchableOpacity>
);
在你的情況下,我有一個疑問。
您是否在 formSignup.js 組件中使用 buttonSubmit.js 組件?
如果是,您可以通過將函數作為 props傳遞來實現它。
//FormSignup.js
const FormSignup = () =>{
const submit = () => {
// some submit logic
};
//render
return (
<View>
....
// if you are using the ButtonSubmit component in FormSignup.js, you
// can get function by props
<ButtonSubmit onPressButton = {()=>submit()}/>
</View>
)
}
//ButtonSubmit.js
const ButtonSubmit = (props) => {
return (
<TouchableOpacity onPress={props.onPressButton}>
<Text>submit</Text>
</TouchableOpacity>
)
}
如果否,您應該單獨編寫該函數並將其導入到 ButtonSubmit.js 組件中
// Utility.js
const submit = () => {
// submit logic
};
export {submit};
//================================//
//ButtonSubmit.js
import { submit } from './path/Utility.js' // import the submit method
const ButtonSubmit = () => {
return (
<TouchableOpacity onPress={()=>submit()}>
<Text>submit</Text>
</TouchableOpacity>
)
}
您可以將函數作為道具傳遞
<buttonSubmit onSubmit={this.submit} />
在你的 buttonSubmit.js 中,你可以在任何你想要的地方從 props 調用它。
//inside somewhere inside buttonSubmit you call:
this.props.onSubmit();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.