React多次渲染选择字段

时间:2018-06-06 12:40:45

标签: javascript reactjs

我需要渲染5个标签,每个标签都应该有一个包含以下选项的选择字段:stringfixedguiddisabled

我实现了以下代码

class renderCampaignCodes extends Component {
    state = {
        defaultCampaigns: [
            { name: 'Campaign Source: utm_source' },
            { name: 'Campaign Medium: utm_medium' },
            { name: 'Campaign Name: utm_campaign' },
            { name: 'Campaign Term: utm_term' },
            { name: 'Campaign Content: utm_content' }
        ],
        defaultTypes: ['string', 'fixed', 'guid', 'disabled']
    }

    render() {
        const { defaultCampaigns } = this.state
        return (
            <Flexbox flexDirection='column' marginTop='20px' width='600px'>
                {
                    defaultCampaigns.map((campaign, idx) => {
                        return (
                            <div key={idx}>
                                <Flexbox justifyContent='space-between'>
                                    <Flexbox marginTop='40px'>
                                        <label>{campaign.name}</label>
                                    </Flexbox>
                                    <Flexbox>
                                        <Field
                                            name='type'
                                            component={renderSelectField}
                                            label='Type'
                                            children={this.state.defaultTypes.map((item, i) => <MenuItem 
                                                key={i}
                                                value={item}
                                                label={item.replace(/^\w/, l => l.toUpperCase())}
                                                primaryText={item.replace(/^\w/, l => l.toUpperCase())}/>)
                                            }
                                        />
                                    </Flexbox>
                                </Flexbox>
                            </div>
                        )
                    })
                }
            </Flexbox>
        )
    }
}

但是,任何选择字段中的选定值都会显示在任何地方: enter image description here

如何防止这种情况发生?

1 个答案:

答案 0 :(得分:1)

看起来每个选项的name属性都被设置为相同,导致它们都从商店/状态获取相同的值(取决于您的实现)。

您需要使用某些内容命名该类型。例如:

<Field
    name={`${idx}.type`}
    component={renderSelectField}
    label='Type'
    children={this.state.defaultTypes.map((item, i) => (
        <MenuItem 
            key={i}
            value={item}
            label={item.replace(/^\w/, l => l.toUpperCase())}
            primaryText={item.replace(/^\w/, l => l.toUpperCase())}
        />
    ))}
/>