我对ReactJS不熟悉,你能帮帮我,告诉我哪里出错了。我想在特定的div中输入详细信息,点击提交按钮,细节应该出现在同一个div中,取代旧的内容
我附上了我的一段代码
<body> <div id="container1"></div> <div id="container2"></div>
<script type="text/babel">
var userName;
var company;
var Example =React.createClass({
display:function(){
userName=this.refs.userName.value;
document.getElementById('para').innerHTML = userName;
company=this.refs.company.value;
document.getElementById('para').innerHTML = company;
},
render:function(){
return(
<div>
<form>
Username <input type="text" ref="userName"></input><br></br>
Comapany <input type="text" ref="company"></input> <br></br>
<button onClick={this.display} type="submit">Display</button>
<Results />
</form>
</div>
);
}
});
var Results = React.createClass({
render: function() {
return (
<div id="results">
<p id="para"> {userName} {company} </p>
</div>
);
}
});
ReactDOM.render(<Example />,document.getElementById('container1'));
ReactDOM.render(<Results/>,document.getElementById('container2'));
</script></body>
答案 0 :(得分:0)
您可以按如下方式解决问题:
class Test extends React.Component {
constructor(props){
super(props);
this.state = {
username: '',
company: '',
showResults: false
}
}
handleChange(field, e){
let state = this.state;
state[field] = e.target.value;
this.setState({state});
}
display(){
this.setState({showResults: !this.state.showResults})
}
render(){
let showResults = this.state.showResults ? <Results {...this.state} /> : "";
return (
<div>
Username <input type="text" name="username" onChange={this.handleChange.bind(this, "username")} value={this.state.username}/><br></br>
Comapany <input type="text" name="company" onChange={this.handleChange.bind(this, "company")} value={this.state.company}/> <br></br>
<button onClick={this.display.bind(this)} type="submit">Display</button>
{showResults}
</div>
)
}
}
class Results extends React.Component {
render(){
return (
<div id="results">
Username : {this.props.username} <br />
Company : {this.props.company}
</div>
)
}
}
React.render(<Test />, document.getElementById('container'));
但我想你不会理解它,因此学习React的第一个基础知识。