我正在尝试在reactJS上实现一个hide / show元素,并且它不会像我预期的那样执行。这是我的代码:
const editDepartment = (props) => (
<div id="editDepartment">
<input type="text" id ='department' placeholder="Enter Department" className="department" value = {ManagerProfile.state.department} onChange={ManagerProfile.updateInputValueDepartment} required />
<button type="submit" id='departmentButton' onClick={ManagerProfile.sendInfo}>Submit</button>
</div>
);
class ManagerProfile extends Component {
constructor(props){
super(props);
this.state={department: "", student: "", isHidden: true};
this.sendInfo = this.sendInfo.bind(this);
this.updateInputValueDepartment =
this.updateInputValueDepartment.bind(this);
this.updateInputValueStudent =
this.updateInputValueStudent.bind(this);
this.editDepartment = this.editDepartment.bind(this);
}
updateInputValueDepartment(evt){
this.setState({department: evt.target.value});
}
updateInputValueStudent(evt){
this.setState({student: evt.target.value});
}
editDepartment(){
this.setState({isHidden: !this.state.isHidden});
}
render() {
return (
<div id ='managerprofile'>
<Menubar />
<div>
<label><b>Department</b></label>
<p> Current department:{this.state.department} </p>
<div>
<button onClick={this.editDepartment} >Edit Department</button>
{!this.state.isHidden && <editDepartment />}
</div>
</div>
<div>
<p><i>Enter your students usernames here to add them to your roster. It should be in the format of username@luther.edu</i></p>
<label><b>Student</b></label>
<input type="text" id ='student' placeholder="Enter Student Id" className="student" value ={this.state.student} onChange={this.updateInputValueStudent.bind(this)} required />
<button type="submit" id='studentButton' onClick ={this.sendInfo.bind(this)}>Submit</button>
</div>
</div>
);
}
sendInfo(){
var config = { headers: {
'Content-Type': 'application/json'}};
axios.post('/api/managerprofile',{
student: this.state.student,
department: this.state.department
}, config)
.then(response => {
if (response.data == 'error'){
alert('Invalid student username. Please enter a different username');
}
else alert('Your changes have been saved');
window.location = '/myprofile';
})
.catch(function (error) {
console.log(error);
});
}
}
export default ManagerProfile;
但是,当我运行文件并单击按钮时,我看到元素显示并消失,因为我单击按钮但标签为空(我在Chrome中的Inspect元素中看到这一点)。那么我错过了什么使标签变空而不是显示它的内容?
非常感谢你!
答案 0 :(得分:0)
是的,它会显示并消失,因为您将其作为表达式的一部分。 替换行:
{!this.state.isHidden && <editDepartment />}
使用
{!this.state.isHidden ? <editDepartment /> : '' }
您的React JSX组件是小写的,React将其解释为HTML元素。将其更改为EditDepartment