class MySelect extends Component {
constructor(params, renderFunction, uniqueId) {
super(params);
this.params = {
...params,
};
this.uniqueId = uniqueId;
this.state = params.state; // not sure why I need this to avoid a null state?
this.updateColours = this.updateColours.bind(this);
// I also tried to "dangerously set innerHTML" with this:
// this.optionElems = '';
// Object.keys(this.params.options).forEach(key => {
// this.optionElems += `<option key="${key}" value="${key}">${this.params.options[key]}</option>`;
// });
}
...
render(params, state) {
const { options } = this.params;
return (
<div className='my-select'>
<select value='BAR' onChange={(event) => this.updateColours(event)} options={options} >
<option value='FOO'>Foo</option>
<option value='BAR'>Bar</option>
{Object.keys(options).forEach(key => {
return <option key={key} value={key}>{options[key]}</option>;
})}
</select>
</div>);
}
它在主应用程序中的调用方式如下:
const myObj = {
ONE: 'First option',
TWO: 'Second option',
}
...
<MySelect wrapper={this.wrapper} state={this.state} options={myObj} />
渲染器时,我希望页面上的选择包含以下内容吗?
<select>
<option value="FOO">Foo</option>
<option value="BAR">Bar</option>
<option value="ONE">First item</option>
<option value="TWO">Second item</option>
</select>
但是我得到的是:
<select>
<option value="FOO">Foo</option>
<option value="BAR">Bar</option>
</select>
注意:
我也尝试过此操作(首先定义选项。):
render(params, state) {
const { options } = this.params;
const optionsItems = Object.keys(options).forEach(key => {
console.log('option: val, name', key, options[key]);
return <option key={key} value={key}>{options[key]}</option>;
});
console.log('options, optionsItems', options, optionsItems);
return (
<div className='my-select'>
<select value='BAR' onChange={(event) => this.updateColours(event)} options={options} >
{optionsItems}
</select>
</div>);
}
options
,params
,optionsItem
不为空,并且全部记录了我所期望的。
我读了无用的东西:
答案 0 :(得分:1)
对我大多数人来说,这很明显:
在我的脚本中,该脚本调用了我的<MySelect>
组件,位于顶部附近;
const options = [
{ value: "ONE", name: 'First item' },
{ value: "TWO", name: 'Second item' },
];
然后在MySelect
组件的呈现功能中:
render(params, state) {
const optionsItems = this.params.options.map((data) => <option key={data.value} value={data.value}>{data.name}</option>);
return (
<div className='my-select'>
<select onChange={(event) => this.updateColours(event)}>
{optionsItems}
</select>
</div>);
答案 1 :(得分:0)
您也可以这样尝试,实际上是一样的,但是如果您要渲染的HTML很复杂,可以尝试一下
render(params, state) {
return (
<div className='my-select'>
<select value='BAR' onChange={(event) => this.updateColours(event)}>
{this.params.options.map((data) => <option key={data.id} value={data.id}>{data.name}</option>)}
</select>
</div>);
我发现不使render函数复杂化很整齐