gpt4 book ai didi

javascript - 无法使用 react 更改元素的值

转载 作者:行者123 更新时间:2023-12-03 07:20:14 24 4
gpt4 key购买 nike

我是 React 的新手,每次单击按钮时我都试图更改元素的值。我在网上查看,我认为它应该可以工作,但由于某种原因不能!提前致谢

import React from 'react';
import ReactDOM from 'react-dom';

const App = () => {
let showDetails = false;
const visabillty = () => {
showDetails = !showDetails;
};

return (
<div style={{textAlign: 'center', margin: '40px'}}>
<h1>Visailty Project</h1>
<button onClick={visabillty}>
{showDetails ? 'show Details' : 'hide Deatils '}
</button>
<h1> {showDetails ? 'hello' : 'buy'}</h1>
</div>
);
};

ReactDOM.render(<App />, document.getElementById('root'));

最佳答案

为了对 React 组件进行持久更改,您应该使用 useState钩。请参阅:state and lifecycle .

尝试以下操作:

import React, { useState } from 'react';
import ReactDOM from 'react-dom';

const App = () => {
const [showDetails, setShowDetails] = useState(false);
const visabillty = () => {
setShowDetails(!showDetails);
};

return (
<div style={{textAlign: 'center', margin: '40px'}}>
<h1>Visailty Project</h1>
<button onClick={visabillty}>
{showDetails ? 'show Details' : 'hide Deatils '}
</button>
<h1> {showDetails ? 'hello' : 'buy'}</h1>
</div>
);
};

ReactDOM.render(<App />, document.getElementById('root'));

关于javascript - 无法使用 react 更改元素的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62605399/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com