我是react世界的新手,我有这样的线路:
<Button onClick={() => console.log("hello")}>Button</Button>
单击后,您将hello在控制台上打印出来。现在将行更改为:
<Button onClick={() => <NewComponent />}>Button</Button>
现在点击按钮,我希望NewComponent渲染。但事实并非如此。
我不确定,为什么会这样。请注意,我在render方法中有上述代码。
我是react世界的新手,我有这样的线路:
<Button onClick={() => console.log("hello")}>Button</Button>
单击后,您将hello在控制台上打印出来。现在将行更改为:
<Button onClick={() => <NewComponent />}>Button</Button>
现在点击按钮,我希望NewComponent渲染。但事实并非如此。
我不确定,为什么会这样。请注意,我在render方法中有上述代码。
您可能希望有一个有状态的组件,在单击按钮后在按钮旁边显示另一个组件。您需要做的就是跟踪按钮是否被点击:
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>
);
}
}
这是一个CodePen来展示它的实际效果。
HTML
<div id="root">loading...</div>
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")
);
改用:
{this.state.clicked && <NewComponent />}
你可以使用withRouter()的react-router-DOM。当我们使用<Route path='/path' component={newComponent} />react-router-dom 传递三个props"history,location 和 match" 时,您可以在 onClick 中使用历史props的push()函数,只需将整个组件传递到withRouter()中即可:
JSX
import { withRouter } from 'react-router-dom' ;
import Button from 'buttonFolder/button.component';
const yourComponent = ({history}) => {
return (
<Button onClick{() => history.push.('/path')}> New componentPage </Button>
)};
export default withRouter(yourComponent);
您需要设置状态以跟踪组件的可见性。默认为 false,onclick 将 state 设置为 true。在你的渲染中做一些像 {this.state.visible ? : 空值}