Reactjs onFocus/onBlur隐藏/显示元素
问题描述:
我有一个两个输入字段,我想要的是如果我点击第一个/如果我输入第一个第二个字段必须隐藏。我在这里有代码,但我认为在语法上有一些错误。对不起,我是这个语言的新手。Reactjs onFocus/onBlur隐藏/显示元素
constructor(props) {
super(props);
this.state = {data: ''};
}
onClick() {
this.setState({ data : 'hidden'});
}
const elements = (
<div>
<label>Pick-up</label>
<PlacesAutocomplete
inputProps={inputProps}
ref="pickupVehicle"
value={this.state.pickup}
onChange={this.handlepickupVehicle}
onClick={this.onClick} />
</div>
<div {this.state.data}>
<label>Drop-off</label>
<PlacesAutocomplete
inputProps={inputProps2}
ref="dropoffVehicle"
value={this.state.destination}
onChange={this.handledropoffVehicle} />
</div>);
然后,如果他已经完成输入或焦点不在那么该字段再次显示它。
答
最简单解决方法是:
constructor(props) {
super(props);
this.state = {data: true};
}
onClick() {
this.setState({ data : false});
}
render() {
const elements = (
<div>
<label>Pick-up</label>
<PlacesAutocomplete
inputProps={inputProps}
ref="pickupVehicle"
value={this.state.pickup}
onChange={this.handlepickupVehicle}
onClick={this.onClick.bind(this)} />
</div>
{this.state.data &&
<div>
<label>Drop-off</label>
<PlacesAutocomplete
inputProps={inputProps2}
ref="dropoffVehicle"
value={this.state.destination}
onChange={this.handledropoffVehicle} />
</div>
}
);
return elements;
}
还有要注意几点:
绑定的onClick功能(使“这个”可以使用):
this.onClick.bind(this)
-
使用
/隐藏元素块{this.state.data && [JSX] }
有条件地显示其状态
如果您还有其他问题,请在这里发帖,这样我们就可以在一起!
答
你应该有逻辑conditional rendering其中在输入字段的焦点之一你设置一些标志为假,并在焦点你设置标志为真。基于所述标志您显示第二输入象下面这样:
render() {
const showSecondInput = this.state.showSecondInput;
return (
<input id="input1" type="text" onFocus={(e) => this.handleFocus(e)} onBlur={(e) => this.handleBlur(e)} .../>
{showSecondInput &&
<input id="input2" type="text" .../>
}
)
};
现在函数的定义应该是这样的:
constructor(props){
super(props);
this.state = {
showSecondInput : true
};
}
function handleFocus(event){
this.state ={
showSecondInput : false
};
}
function handleBlur(event){
this.state ={
showSecondInput : true
};
}
对于你的问题,试试下面的代码:
constructor(props) {
super(props);
this.state = {data: true};
this.onClick= this.onClick.bind(this);
}
onClick() {
this.setState({ data : false});
}
const elements = (
<div>
<label>Pick-up</label>
<PlacesAutocomplete
inputProps={inputProps}
ref="pickupVehicle"
value={this.state.pickup}
onChange={this.handlepickupVehicle}
onClick={this.onClick} />
</div>
{this.state.data &&
<div>
<label>Drop-off</label>
<PlacesAutocomplete
inputProps={inputProps2}
ref="dropoffVehicle"
value={this.state.destination}
onChange={this.handledropoffVehicle} />
</div> });
您发布的代码在语法上不正确。你在'React.Component'类定义的主体内部有'jsx'语句... – Pineda
哦,对不起,我忘了补充说该字段在函数内部。我的错。 – Deee
@Deee请添加更多代码,我们可以看到'render'函数 –