我有signup.jsx
import React from "react"
import { render } from "react-dom"
import SignupContainer from "./containers/SignupContainer"
class Signup extends React.Component {
user(){
this.props.type='user';
}
hotel(){
this.props.type='hotel';
}
render() {
return (
<div>
Registration Type :
<br></br>
<button onClick={this.user}>user</button>
<button onClick={this.hotel}>hotel</button>
<SignupContainer type={this.props.type}/>
<h1>Signup</h1>
</div>
);
}
}
render(<Signup type='user'/>, document.getElementById('Signup'))
我的SignupContainer.jsx
import React from "react"
import Headline from "../components/Headline"
export default class SignupContainer extends React.Component {
render() {
if(this.props.type=='user'){
return (
<div className="container">
<div className="row">
<div className="col-sm-12">
<form action="/loginapp/" method="POST">
First Name:
<input type="text" name="first_name">
</input>
<br></br>
Last Name:
<input type="text" name="last_name"/>
<br></br>
Gender:
<input type="radio" name="gender" value="male" />Male
<input type="radio" name="gender" value="female" /> Female
<br></br>
<input type="submit" value="Submit"/>
</form>
</div>
</div>
</div>
);
} else if(this.props.type=='hotel'){
return(<h1>{this.props.type}</h1>);
}
}
}
我想要的是当我点击用户按钮然后它应该向我显示注册表单,当我点击酒店按钮时它应该打印酒店而不重新加载页面。
答案 0 :(得分:1)
在React中,props
从父级传递给子级,应该被认为是不可变的。另一方面,组件在内部使用state
,可以使用this.setState()
进行更新,从而触发重新渲染。此外,在使用本机JavaScript类时,如果希望this
引用类,则需要将类方法绑定到类。所以在你的情况下,这样的事情应该有效:
class Signup extends React.Component {
constructor(props) {
super(props);
this.state = { // this is your default state
type: 'user'
}
}
user() {
this.setState({
type: 'user'
})
}
hotel() {
this.setState({
type: 'hotel'
})
}
render() {
return ( < div >
Registration Type:
< br > < /br>
<button onClick={this.user.bind(this)}>user</button >
<button onClick = {this.hotel.bind(this)}>hotel</button>
<SignupContainer type={this.state.type} />
<h1> Signup </h1>
</div>
);
}
}
render( < Signup type = 'user' / > , document.getElementById('Signup'))
&#13;
答案 1 :(得分:0)
尝试在安装组件后不更改自有组件的道具。而是使用状态。
import React from "react"
import {render} from "react-dom"
import SignupContainer from "./containers/SignupContainer"
class Signup extends React.Component {
constructor(props){
super(props);
this.state = {type : this.props.type};
}
user() {
this.setState({type: 'user'});
}
hotel() {
this.setState({type: 'hotel'});
}
render() {
return ( <div >
Registration Type:
<br />
<button onClick={this.user}>user</button >
<button onClick = {
this.hotel
} > hotel </button>
<SignupContainer type={this.state.type}/ >
<h1> Signup </h1>
</div>
);
}
}
render( < Signup type = 'user' / > , document.getElementById('Signup'))