bat*_*man 26 javascript reactjs
我是新的反应世界,我有这样的行:
<Button onClick={() => console.log("hello")}>Button</Button>
Run Code Online (Sandbox Code Playgroud)
点击后,您将hello在控制台上打印出来.现在将行更改为:
<Button onClick={() => <NewComponent />}>Button</Button>
Run Code Online (Sandbox Code Playgroud)
现在单击按钮,我希望NewComponent渲染.但事实并非如此.
我不确定,为什么会这样.请注意,我在render方法中有上面的代码.
Fel*_*ing 57
您可能希望有一个有状态组件,在单击按钮后显示该按钮旁边的其他组件.您需要做的就是跟踪按钮是否被点击:
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
showComponent: false,
};
this._onButtonClick = this._onButtonClick.bind(this);
}
_onButtonClick() {
this.setState({
showComponent: true,
});
}
render() {
return (
<div>
<Button onClick={this._onButtonClick}>Button</Button>
{this.state.showComponent ?
<NewComponent /> :
null
}
</div>
);
}
}
Run Code Online (Sandbox Code Playgroud)
这是一个CodePen演示它的实际应用。
的HTML
<div id="root">loading...</div>
Run Code Online (Sandbox Code Playgroud)
JSX
class NewComponent extends React.Component {
render() {
return (
<div {...this.props}>
new component
</div>
);
}
}
class Button extends React.Component {
render() {
return (
<button {...this.props}>
click
</button>
);
}
}
class App extends React.Component {
constructor() {
super();
this.state = {
clicked: false
};
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
this.setState({
clicked: true
});
}
render() {
return (
<div>
<Button onClick={this.handleClick} />
{this.state.clicked ? <NewComponent /> : null}
</div>
);
}
};
React.render(
<App />,
document.getElementById("root")
);
Run Code Online (Sandbox Code Playgroud)