如何在每次点击按钮时渲染react组件中的react组件?



我是React的新手,正在开发Nextjs应用程序。每次点击按钮时,我都有渲染React组件的问题-组件不显示。但是,当我检查页面并记录组件时,它显示它是由函数为此目的返回的。我正在使用react hooks -useStateuseEffect. 我想要的是,每次按钮"+",则会显示一个新的needdedproductsfield组件。这是一个简单的表单,用于添加来自用户的菜谱。不知是否有人能帮忙。谢谢!

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; ```

您的状态和useEffect可能有点混乱,但您不需要所有这些

就像这样更新你的组件:

function AddRecipeForm() {
const [fieldsNum, setFieldsNum] = useState(1);
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={() => setFieldsNum(fieldsNum + 1)}
>
+
</Button>
<p>
{[...Array(fieldsNum).keys()].map(_field => (
<NeededProductsField />
))}
</p>
</Form.Group>
<Button variant="primary" type="submit">
Запиши
</Button>
</Form>
);
}

最新更新