我有一个 React Redux 应用程序,它有各种选择框。现在我把它硬编码在 js 文件中。 我需要这些用于以下页面:编辑个人资料、查看个人资料、搜索选择.. 我认为每一页都有这么长的列表是没有意义的。
如何外部化这些选项 - 我想将其存储在单个 JS 文件中,并仅在需要时使用这些选项。
请注意,我的问题不是如何创建选择组件。我已经在下面做了。问题是如何拉<option>
来自外部来源的列表。
我的代码示例是:
import React from 'react'
import PropTypes from 'prop-types'
import Select from '../others/input/select'
const InputCasteChristian = ({ value, change }) => (
<div className="edit_caste_div">
<Select
placeholder="Select option"
value={value}
valueChange={e => change('caste', e)}
className="edit_caste mb-2"
>
<option value="" disabled selected>
Select Caste
</option>
<option>Anglo-Indian</option>
<option>Born Again</option>
<option>Brethren</option>
<option>CSI</option>
<option>Unspecified</option>
</Select>
</div>
)
InputCasteChristian.propTypes = {
value: PropTypes.string.isRequired,
change: PropTypes.func.isRequired,
}
export default InputCasteChristian
更新
import ReligionInput from './religion-input'
...
...
return (
<div>
<Title
value="Edit profile"
..
...
<div className="profile_right">
....
<ReligionInput value={religion} change={this.change} />
...
...
..
const mapStateToProps = store => ({
ud: store.User.user_details,
tags: store.User.tags,
session: store.User.session,
})
export default connect(mapStateToProps)(EditProfile)
export { EditProfile as PureEditProfile }
最佳答案
您应该能够将选项作为数组传递,并且该组件不需要知道您如何创建此列表,您只需将其传递到此处即可。 并使用 map 功能,您可以创建选项列表。
import React from 'react'
import PropTypes from 'prop-types'
import Select from '../others/input/select'
const InputCasteChristian = ({ value, change, options }) => (
<div className="edit_caste_div">
<Select
placeholder="Select option"
value={value}
valueChange={e => change('caste', e)}
className="edit_caste mb-2"
>
{options.map((a, index) => {
return (
<option key={index}>{a}</option>
);
})}
</Select>
</div>
)
InputCasteChristian.propTypes = {
value: PropTypes.string.isRequired,
change: PropTypes.func.isRequired,
}
export default InputCasteChristian
这是调用者组件,看看我如何填充选项:
import React, { Component } from 'react';
import InputCasteChristian from './InputCasteChristian';
import { connect } from 'react-redux';
class InputCasteChristianCaller extends Component {
constructor(props) {
super(props);
this.state = {
value: '',
options: props.options
};
}
render() {
return (
<InputCasteChristian
value={this.state.value}
change={() => { }}
options={this.state.options} />
);
}
}
function mapStateToProps(state, ownProps) {
return {
options: state.options
};
}
function mapDispatchToProps(dispatch) {
return {
dispatch: dispatch
};
}
export default connect(mapStateToProps, mapDispatchToProps)(InputCasteChristianCaller);
我在构造函数中创建了一个数组对象,您可以像我一样创建这个列表,或者您可以从 ajax 调用中获取它,...
关于javascript - 如何在 React 应用程序中外部化选择选项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51914292/