显示/隐藏基于从 Form.check 中选中/取消选中的 Form.control 反应引导程序



我对反应和引导很陌生。我想知道 - 当选中或取消选中 Form.check 时,如何控制 Form.control 的可见性。

我想在选中复选框时显示 Form.Control,然后在取消选中复选框时将其隐藏。我试图通过设置状态来控制可见性,但到目前为止我没有成功。

这是我尝试过的:

import React from 'react';
import { Row, Form, Col, Button, Container } from 'react-bootstrap';
class MyCustomClass extends React.Component {
constructor(props) {
super(props);
this.initialState = {
Check: false,
DisplayUrl: ''
}
this.handleChange = this.handleChange.bind(this);
handleChange(event)
{
const name = event.target.name;
const value = event.target.type === "checkbox" ? event.target.checked : event.target.value;
this.setState(
{
[name]: value
})}
render()
{    
let controlvisibility;
if (this.state.Check) {
controlvisibility = "visible";
}
else {
controlvisibility = "hidden"; //I am not sure, if this can be used.
}
return (
<div>
<br />             
<Form>
<Form.Group as={Row}>
<Container>
<Row>
<Form.Check inline
type="Checkbox"
label="See the Url"
name="Check"
id="cbDisplayUrl"
checked={this.state.Check}
onChange={this.handleChange}
/>
<Form.Control inline
type="text"
name="DisplayUrl"
onChange={this.handleChange}
value={this.state.DisplayUrl}
placeholder="The Navigation Url" />
</Row>
</Container>
</Form.Group>
</Form>
</div>
)
} 

}

您已经在使用this.state.Check来控制复选框的值。所以你可以像这样隐藏/显示给Form.Control

<Row>
<Form.Check inline
type="Checkbox"
label="See the Url"
name="Check"
id="cbDisplayUrl"
checked={this.state.Check}
onChange={this.handleChange}
/>
{this.state.Check &&
<Form.Control inline
type="text"
name="DisplayUrl"
onChange={this.handleChange}
value={this.state.DisplayUrl}
placeholder="The Navigation Url" />
}
</Row> 

这将在this.state.Check的值为 true 时创建Form.Control,并在this.state.Check为 fale 时将其删除

首先,你不应该在构造函数中定义渲染和处理程序!! 你应该在 React 中了解状态: 试试这个:

import React from 'react';
import { Row, Form, Col, Button, Container } from 'react-bootstrap';
class MyCustomClass extends React.Component {
constructor(props) {
super(props);
this.state = {
Check: false,
DisplayUrl: ''
}
this.handleChange = this.handleChange.bind(this);
}

handleChange(event) {
const name = event.target.name;
const value = event.target.type === "checkbox" ? event.target.checked : event.target.value;
this.setState({
[name]: value
})
}
render() {
return (
<div>
<br />
<Form>
<Form.Group as={Row}>
<Container>
<Row>
<Form.Check inline
type="Checkbox"
label="See the Url"
name="Check"
id="cbDisplayUrl"
checked={this.state.Check}
onChange={this.handleChange}
/>
{this.state.Check && <Form.Control inline
type="text"
name="DisplayUrl"
onChange={this.handleChange}
value={this.state.DisplayUrl}
placeholder="The Navigation Url" />}
</Row>
</Container>
</Form.Group>
</Form>
</div>
)
}
}
export default MyCustomClass;

最新更新