[英]How to render the same component with different props
I'm learning react recently.我最近在学习反应。
I want to render a component with different props again but it doesn't work.我想再次渲染具有不同道具的组件,但它不起作用。
Here is the js code这是js代码
// page container
class Page extends React.Component {
constructor(props) {
super(props);
console.log(this.props.type);
this.state = {
type: this.props.type
}
} // end of constructor
render() {
return (
<div className={this.state.type}>
</div>
);
} // end of render()
} // end of componenet: page container
function show() {
ReactDOM.render(<Page type="page1"/>, $("#main")[0]);
}
ReactDOM.render(<Page type="homepage" />, $("#main")[0]);
the html includes a button which will call the show() when clicked. html 包含一个按钮,单击时将调用 show()。
How to make it render again when I click on the button单击按钮时如何使其再次呈现
React state isn't supposed to be modified from the outside.不应从外部修改 React 状态。 In this case there are no reasons to place a button outside React application.在这种情况下,没有理由在 React 应用程序之外放置按钮。 When it's place inside, it can update the state:当它放在里面时,它可以更新状态:
class Page extends React.Component {
this.state = {
type: 'homepage'
};
render() {
return <>
<div className={this.state.type}></div>
<button onClick={() => this.setState({ type: 'page1' })}>click</button>
<>;
}
}
ReactDOM.render(<Page />, $("#main")[0]);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.