我是新手,要做出反应。我一直在尝试渲染新组件。我有两个包含两个不同组件的文件。 Fmueditor.js和Viewfmu.js。 想要使用Fmueditor.js中VIEW按钮上的click事件来呈现Viewfmu.js组件。 请帮助我弄清楚我在做什么错。
import Viewfmu from './Viewfmu'
class Fmueditor extends Component {
constructor(props){
super(props)
this.state = {
message: 'FMU List'
}
}
render() {
return (
<div>
<h1>{this.state.message}</h1>
<ButtonToolbar>
<Button variant="primary" onClick ={this._onButtonClick} >VIEW</Button>
<Button variant="primary">ASSIGN</Button>
</ButtonToolbar>
<ListGroup>
<ListGroup.Item>FMU1</ListGroup.Item>
<ListGroup.Item variant="primary">FMU2</ListGroup.Item>
<ListGroup.Item action variant="secondary">FMU3</ListGroup.Item>
</div>
)
}
}
export default Fmueditor
Viewfmu.js
class Viewfmu extends Component {
constructor(props){
super(props)
this.state = {
showComponent: false,
};
this._onButtonClick = this._onButtonClick.bind(this);
}
_onButtonClick() {
this.setState({
showComponent: true,
});
}
render() {
return (
<div>
<h1>{this.state.message}</h1>
<Table striped bordered hover>
<thead>
<tr>
<th>#</th>
<th>First Name</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>Mark</td>
<td>Otto</td>
<td>@mdo</td>
</tr>
</tbody>
</Table>
</div>
)
}
}
export default Viewfmu
答案 0 :(得分:2)
您可以通过管理state
变量来简单地显示/隐藏组件。
使用showViewfmu
状态变量。
this.state = {
message: 'FMU List',
showViewfmu: false
}
点击按钮state
_onButtonClick(){
this.setState({showViewfmu: !this.state.showViewfmu});
}
添加以下代码以显示/隐藏组件
{this.state.showViewfmu && <Viewfmu />}
您的完整代码应如下所示……
import Viewfmu from './Viewfmu'
class Fmueditor extends Component {
constructor(props){
super(props)
this.state = {
message: 'FMU List',
showViewfmu: false
}
}
_onButtonClick(){
this.setState({showViewfmu: !this.state.showViewfmu});
}
render() {
return (
<div>
<h1>{this.state.message}</h1>
<ButtonToolbar>
<Button variant="primary" onClick={this._onButtonClick} >VIEW</Button>
<Button variant="primary">ASSIGN</Button>
</ButtonToolbar>
<ListGroup>
<ListGroup.Item>FMU1</ListGroup.Item>
<ListGroup.Item variant="primary">FMU2</ListGroup.Item>
<ListGroup.Item action variant="secondary">FMU3</ListGroup.Item>
</ListGroup>
{this.state.showViewfmu && <Viewfmu />}
</div>
)
}
}
export default Fmueditor
您还可以定义routes
,并根据routes
加载组件。
希望这对您有用!