我有兩個React組件
class App extends React.Component {
render() {
return (
<div id="appWrapper"/span>>
<ConfigureWindow />
<button id="configureClocksButton"/span>> 配置時鐘</button>。
<section id="clocksHere"/span>> </section>>
</div>
);
}
const ConfigureWindow = () => (
<div id="configureWindowWrapper"/span>>
<div id="configureWindow"/span>>
<section id="addCitySection">/span>TODO: 添加一個城市</section>
<div id="verticalLine"/span>> </div>>
<section id="listOfCities">/span>
<header>/span>
<h1>現有城市</h1>
<div id="closeConfigureWindowWrapper">/span>
<img src=".srcimagesexit. png" id="closeConfigureWindow" alt=" />
</div>
</header>/span>
<section id="availableCities"/span>> </section>>
</section>/span>
</div>
</div>
);
我想在 "configureClocksButton "時顯示 "ConfigureWindow"。我試圖用props、state和一個函式來執行它,但得到了錯誤。如果你能給我解釋一下如何用React函式創建新的React組件,那就更好了。
uj5u.com熱心網友回復:
你可能想使用React.JS事件onClick(https://reactjs.org/docs/handling-events.html),以及一個狀態來存盤動作。要創建一個函陣列件,你只需回傳你想要渲染的JSX,并使用鉤子(https://reactjs.org/docs/hooks-intro.html),然后進行有條件的渲染(https://reactjs.org/docs/conditional-rendering.html):
const App = (/span>) => {
const [toggleConfiguration, setToggleConfiguration] = useState(false)
return (
<div id="appWrapper"/span>>
{toggleConfiguration && <ConfigureWindow />}。
<button onClick{()=> setToggleConfiguration(true)} id="configureClocksButton">配置時鐘</button>
<section id="clocksHere"/span>> </section>>
</div>
);
}
uj5u.com熱心網友回復:
有點難以理解你的帖子,但我認為你想點擊帶有id="configureClocksButton"的按鈕并有條件地渲染ConfigureWindow組件。
你可以通過一些布爾狀態,一個點擊處理程式來切換狀態,以及一些條件性渲染來實作這一目標。
class App extendsReact.Component {
this.state = {
showConfigureWindow: false,
}
toggleShowConfigureWindow = () => this. setState(span class="hljs-params">prevState => ({
showConfigureWindow: !prevState.showConfigureWindow,
}))
render(){
return (
<div id="appWrapper"/span>>
{showConfigureWindow && <ConfigureWindow />}。
<button
id="configureClocksButton"。
onClick={this.toggleShowConfigureWindow}。
>
配置時鐘
</button>配置時鐘
<section id="clocksHere"/span>> </section>>
</div>
);
}
一個函陣列件相當于:
const App = (/span>) => {
const [showConfigureWindow, setShowConfigureWindow] = React.useState(false)。
const toggleShowConfigureWindow = () => setShowConfigureWindow(show => ! show)。)
return (
<div id="appWrapper">/span>
{showConfigureWindow && <ConfigureWindow />}。
<button
id="configureClocksButton"。
onClick={toggleShowConfigureWindow}。
>
配置時鐘
</button>配置時鐘。
<section id="clocksHere"/span>> </section>>
</div>
);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/322726.html
標籤:
