gpt4 book ai didi

javascript - 使用 redux 表单添加和编辑多个主题

转载 作者:行者123 更新时间:2023-11-30 20:26:47 25 4
gpt4 key购买 nike

用例是添加主题按钮,单击该按钮时应显示用于添加主题的表单。当用户填写主题表单并点击保存按钮时,该主题应显示在带有编辑按钮而不是添加按钮的输入框中。可以有多个主题。例如,如果我已经有 4 个主题或在添加后保存了它们,那么它们应该显示为带有编辑按钮。我的做法甚至没有触发 handleChange

我为此创建了一个沙箱,就在这里

https://codesandbox.io/s/koqqvz2307

代码

class FieldArray extends React.Component {
state = {
topics: [],
topic: ""
};

handleChange = e => {
console.log("handleChange", e);
this.setState({ topic: { ...this.state.topic, topic: e.target.value } });
};

handleSubmit = e => {
e.preventDefault();
console.log("state of topics array with multiple topics");
};

render() {
return (
<div>
<FieldArrayForm
topics={this.state.topics}
topic={this.state.topic}
handleChange={this.handleChange}
handleSubmit={this.handleSubmit}
/>
</div>
);
}
}

export default FieldArray;



const renderField = ({ input, label, type, meta: { touched, error } }) => (
<div>
<label>{label}</label>
<div>
<input {...input} type={type} placeholder={label} />
{touched && error && <span>{error}</span>}
</div>
</div>
);

const renderTopics = ({
fields,
meta: { error },
handleChange,
handleSubmit,
topic
}) => (
<ul>
<li>
<button type="button" onClick={() => fields.push()}>
Add Topic
</button>
</li>
{fields.map((topicName, index) => (
<li key={index}>
<span>
<Field
name={topicName}
type="text"
onChange={handleChange}
component={renderField}
label={`Topic #${index + 1}`}
/>
<span>
<button
type="button"
title="Remove Hobby"
onClick={() => fields.remove(index)}
>
Remove
</button>
{topic ? (
<button type="button" title="Add" onSubmit={handleSubmit}>
Edit
</button>
) : (
<button type="button" title="Add" onSubmit={handleSubmit}>
Add
</button>
)}
</span>
</span>
</li>
))}
{error && <li className="error">{error}</li>}
</ul>
);

const FieldArraysForm = props => {
const { handleSubmit, pristine, reset, submitting } = props;
return (
<form onSubmit={handleSubmit}>
<FieldArray name="topic" component={renderTopics} />
</form>
);
};

export default reduxForm({
form: "fieldArrays", // a unique identifier for this form
validate
})(FieldArraysForm);

使用 redux-form 时如何保存和显示多个主题?我试图从 fieldarray 中获取概念,但我还做不到。

最佳答案

您的 handleChange 未定义,这就是您的函数未被调用的原因。

如果您希望 renderTopics 接收一个 handleChange 函数,您应该将 handleChange 属性传递给 FieldArray 组件(根据 redux-form docs ):

const FieldArraysForm = props => {
const { handleChange, handleSubmit, pristine, reset, submitting } = props;
return (
<form onSubmit={handleSubmit}>
<FieldArray name="topic" component={renderTopics} handleChange={handleChange} />
</form>
);
};

或者,您可以简单地将所有属性从 FieldArraysForm 传递到 FieldArray 组件:

const FieldArraysForm = props => (
<form onSubmit={handleSubmit}>
<FieldArray name="topic" component={renderTopics} {...props} />
</form>
);

关于javascript - 使用 redux 表单添加和编辑多个主题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50814655/

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