![](/img/trans.png)
[英]How to pass props onClick from one component to another in React JS
[英]How to replace one React Component with another OnClick?
我有一個“注冊”按鈕。 單擊它時,我希望它呈現一個名為“ SignUp”的新組件。 我希望新組件替換“注冊”按鈕。
當前,我正在使用setState,以便在單擊按鈕時呈現一個新組件。 但是,按鈕不會被替換,“ SignUp”組件只是在按鈕旁邊呈現。 對我來說,用呈現的新組件替換按鈕可能是個好方法?
我在下面提供了我的代碼:
export default class SignUpSignIn extends Component {
constructor() {
super();
this.state = {
clicked: false
};
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
this.setState({
clicked: true
});
}
render () {
return (
<div id="SignUpSignInDiv">
<Col md="12" sm="12" xs="12" className="text-center">
<div onClick={this.handleClick}>
{this.state.clicked ? <SignUp /> : null}
<Button id="SignUpButton" color="primary"> Sign Up </Button>
</div>
</Col>
</div>
)
}
}
好吧,您不是有條件地渲染兩個組件,而僅是SignUp
。 在state.clicked === false
時, state.clicked === false
在三元數中使用null
,而應顯示登錄按鈕:
render () {
return (
<div id="SignUpSignInDiv">
<Col md="12" sm="12" xs="12" className="text-center">
{this.state.clicked ? (
<SignUp />
) : (
<Button id="SignUpButton" color="primary" onClick={this.handleClick}> Sign Up </Button>
)}
</Col>
</div>
)
}
一種方法是像這樣,我還沒有測試它,但它應該可以工作
render () {
let show = <div></div>
if(this.state.clicked){
show = <SignUp />
}
return (
<div id="SignUpSignInDiv">
<Col md="12" sm="12" xs="12" className="text-center">
{show}
<Button id="SignUpButton" color="primary" onClick={this.handleClick}> Sign Up </Button>
</Col>
</div>
)
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.