【发布时间】:2021-11-08 01:49:41
【问题描述】:
我是 React 的新手,正在开发 Nextjs 应用程序。我有每次单击按钮时渲染一个反应组件的问题 - 该组件只是不显示。但是,当我检查页面并记录该组件时,它显示它是为此目的由函数返回的。我正在使用反应挂钩 - useState 和 useEffect。我想要发生的是,每次单击“+”按钮时,都会显示一个新的 NeededProductsField 组件。这是一个简单的表格,用于添加用户的食谱。我想知道是否有人可以提供帮助。 谢谢!
import FloatingLabel from 'react-bootstrap/FloatingLabel';
import Button from 'react-bootstrap/Button';
import { useState, useEffect } from 'react';
import NeededProductsField from './NeededProductsField';
function AddRecipeForm() {
const[newFieldVisible, setNewFieldVisible] = useState(false);
function generateNewField(stat) {
if (stat === true) {
return <NeededProductsField />;
}
}
function showField(state) {
useEffect(() => {
if (state === true) {
console.log("State changed to TRUE? " + newFieldVisible);
// console.log(generateNewField(newFieldVisible));
generateNewField(newFieldVisible);
setNewFieldVisible(false);
}
}, [newFieldVisible]);
}
return (
<Form>
<Form.Group className="mb-3" controlId="addRecipe">
<Form.Label>Име на рецептата</Form.Label>
<Form.Control type="title" placeholder="Добави име" />
</Form.Group>
<Form.Group className="mb-3" controlId="neededProducts">
<Form.Label>Необходими продукти</Form.Label>{' '}
<Button variant="primary" size="sm" onClick={() => setNewFieldVisible(true)}>+</Button>{' '}
<p>
<NeededProductsField />
</p>
{ showField(newFieldVisible) }
</Form.Group>
<Button variant="primary" type="submit">
Запиши
</Button>
</Form>
);
}
export default AddRecipeForm; ```
And this is my NeededProductsField component:
```import Form from 'react-bootstrap/Form';
import Row from 'react-bootstrap/Row';
import Col from 'react-bootstrap/Col';
function NeededProductsField(props) {
return (
<Row>
<Col xs={7}>
<Form.Control placeholder="Име" />
</Col>
<Col>
<Form.Control placeholder="Количество" />
</Col>
<Col>
<Form.Control placeholder="М. ед." />
</Col>
</Row>
);
}
export default NeededProductsField; ```
【问题讨论】:
-
所以你想在每次点击
+时创建多个NeededProductsField?还是只想显示一个NeededProductsField? -
我希望每次点击 + 按钮时只显示一个 NeededProductsField。
-
点击
+后再添加一个还是再隐藏一次? -
直接添加,不隐藏。
标签: reactjs react-hooks event-handling next.js