【问题标题】:React Typescript: How to dynamically add form elements with an onClick function for a Button element?React Typescript:如何使用 Button 元素的 onClick 函数动态添加表单元素?
【发布时间】:2019-05-05 19:37:17
【问题描述】:

我想动态生成TextFields,然后将它们的值存储在状态的数组中。

我的进口:

import TextField from '@material-ui/core/TextField';
import Button from '@material-ui/core/Button';

我在 TextField 下方创建了一个按钮。我想在单击按钮后动态添加 TextFields。

TextField required={true}
    onChange={e => this.state.book_authors.push(e.target.value)}
    className={this.props.classes.textField}
    label={"Author"}
    variant="outlined"
    type="text"/>

<Button
    variant="contained" color="primary"
    action={() => this.handleAddAuthorField()}
    className={this.props.classes.button}
>
    Add Author
</Button>

我的方法:

 handleAddAuthorField(): JSX.Element {
    return (
        <Row>
            <TextField
                required={true}
                onChange={e => this.state.book_authors.push(e.target.value)}
                className={this.props.classes.textField}
                label={"Author"}
                variant="outlined"
                type="text"
            />
        </Row>

    )

}

状态 book_authors 将 TextField 输入存储为一个数组。

public state: IsBookState = {
    book_authors: [],
};

单击按钮后,TextField 没有生成。

【问题讨论】:

    标签: reactjs typescript material-ui


    【解决方案1】:

    这里有几件事有点不对劲,但让我们专注于这个问题。我觉得我错过了一些代码,我没有看到文本字段的呈现位置。

    您需要类似以下内容:

    this.state = { authors: [] } // Set in constructor
    
    render() {
        const { authors } = this.state;
    
        return (
            <div>
                {authors.map(author => (
                    <TextField author={author} />
                )}
                <Button onClick={this.handleAddAuthorField}>Add author field</Button>
            </div>
        )
    }
    

    这段代码非常精简,但我的意思是你需要在某个地方渲染你的组件——就像我说的我不确定我是否完全理解你在问什么,请澄清预期的功能到底是什么。

    【讨论】:

    • TextField中的author={author}是什么意思?
    • 它在TextField组件中设置了一个名为“author”的prop,当我们用map遍历它时,它将是“authors”数组的当前元素。因此,要在组件中显示数据,您可以执行 &lt;div&gt;{this.props.author.name}&lt;/div&gt; 假设我们正在映射的数组的每个元素都有一个“名称”属性。 @MuizUvais
    猜你喜欢
    • 2013-05-20
    • 1970-01-01
    • 2019-02-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多