如何根据条件语句添加 React 组件,基于可变计数器评估布尔值
Posted
技术标签:
【中文标题】如何根据条件语句添加 React 组件,基于可变计数器评估布尔值【英文标题】:How to add React components based on conditional statements evaluating a boolean based on a changable counter 【发布时间】:2020-11-05 18:22:54 【问题描述】:早上好,
我正在尝试根据计数器值添加React
组件,然后使用条件语句来确定它们是否被呈现。换句话说,我想在单击“+”时在组件下方添加组件,然后在单击“x”时删除这些元素。我尝试使用的代码如下:
let differentials = 0;
const diffAdded = () =>
if (differentials < 2)
differentials++;
const diffRemoved = () =>
if (differentials > 0)
differentials--;
return (
<article className="addJob">
<header className="margin title">
<p>Add new job:</p>
</header>
<main>
<form>
<section className="form-group">
<label className="margin" htmlFor="name">Job name</label>
<input type="text" id="name" className="form-control anInput"
placeholder="Enter job title" required />
<label className="margin" htmlFor="hourly">Hourly rate</label>
<input type="number" id="hourly" className="form-control anInput"
placeholder="$##.##" required />
</section>
<section>
<label className="margin">Shift/night differential?</label>
<i className="fa fa-plus add-button margin" aria-hidden="true" onClick=() =>
diffAdded()></i>
</section>
//this section is the one I want to changed based on counter value
<section>
differentials > 0 && <DiffSection id="diff1" diffRemoved=() =>
diffRemoved()/>
differentials > 1 && <DiffSection id="diff2" diffRemoved=() =>
diffRemoved()/>
</section>
<section className="submit-button" onClick=() => jobAdded(
document.getElementById('name'),
document.getElementById('hourly'),
document.getElementById('diff1'),
document.getElementById('diff2')
)
>
<p>Submit</p>
</section>
</form>
</main>
<section className="footer" onClick=() => nameClicked()>
<span className="user-name">props.userData.name</span>
</section>
</article>
);
我通过实例化一个空数组然后在单击“+”图标时推送组件来尝试同样的事情。
这是我在代码沙箱中尝试做的简化版本:
https://codesandbox.io/s/muddy-mountain-rll71?fontsize=14&hidenavigation=1&theme=dark
我需要做什么才能让它工作?
谢谢
【问题讨论】:
【参考方案1】:更改局部变量不会触发组件的生命周期,这可以通过使用像useState
这样的 React API 来完成。
这是React的基本概念,你应该参考State and Lifecycle,Component State。
export default function App()
const [counter, setCounter] = useState(0);
const plusClicked = () =>
if (counter < 2)
setCounter(p => p + 1);
console.log(counter);
;
const minusClicked = () =>
if (counter > 0)
setCounter(p => p - 1);
console.log(counter);
;
return (...)
【讨论】:
以上是关于如何根据条件语句添加 React 组件,基于可变计数器评估布尔值的主要内容,如果未能解决你的问题,请参考以下文章
使用 Apollo 客户端根据 React 组件中的节点类型值发出条件 GraphQL 请求