[英]How to render same react component for different routes with different value props?
[英]How to render the same component with different props
我最近在學習反應。
我想再次渲染具有不同道具的組件,但它不起作用。
這是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]);
html 包含一個按鈕,單擊時將調用 show()。
單擊按鈕時如何使其再次呈現
不應從外部修改 React 狀態。 在這種情況下,沒有理由在 React 應用程序之外放置按鈕。 當它放在里面時,它可以更新狀態:
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.