javascript-如何将id属性应用于ReactJS组件的子元素?
作者:互联网
所以我有一个下拉组件:
import React from 'react';
import { PropTypes } from 'prop-types';
export default class Dropdown extends React.Component {
constructor(props) {
super(props);
this.state = {
value: this.props.selectedDropdownValue,
};
this.handleChange = this.handleChange.bind(this);
}
handleChange(e) {
this.setState({
value: e.target.value,
});
this.props.onChange(e.target.value);
}
render() {
let disabled = false;
let dropdownOptions = null;
const { options } = this.props;
// Disable dropdown is the disabled attribute is added
if (options) {
dropdownOptions = this.props.options.map((option) =>
<option value={option.key} key={option.key} >{option.display}</option>,
);
} else {
// Setting default options
const defaultOptions = [
{ key: '', display: 'Please configure defaultOptions' },
];
disabled = true;
dropdownOptions = defaultOptions.map((option) =>
<option value={option.key} key={option.key} >{option.display}</option>,
);
}
return (
<select
value={this.state.value}
onChange={this.handleChange}
disabled={disabled}
>
{ dropdownOptions }
</select>
);
}
}
Dropdown.propTypes = {
options: PropTypes.arrayOf(PropTypes.object),
onChange: PropTypes.func,
selectedDropdownValue: PropTypes.string,
};
Dropdown.defaultProps = {
options: undefined,
onChange: this.handleChange,
selectedDropdownValue: '',
};
这是我在视图中呈现下拉菜单的方式:
import React from 'react';
import { PropTypes } from 'prop-types';
import Dropdown from 'components/Dropdown';
class Anish extends React.Component {
render() {
return (
<div>
<div>
Value Selected: {this.props.selectedDropdownValue}
</div>
<label htmlFor={'dropdownId1'}>Sort by: </label>
<Dropdown
id="dropdownId1"
options={[
{ key: '', display: 'Please select a value' },
{ key: 'NJ', display: 'New Jersey' },
{ key: 'NY', display: 'New York' },
]}
onChange={this.props.onSetDropdownValue}
/>
</div>
);
}
}
Anish.propTypes = {
selectedDropdownValue: PropTypes.string,
onSetDropdownValue: PropTypes.func.isRequired,
};
Anish.defaultProps = {
selectedDropdownValue: '',
};
export default Anish;
这是在浏览器中呈现下拉菜单和标签的方式:
因此,我该如何应用< Dropdown />上的ID到< select>在里面吗?
任何帮助表示赞赏.
解决方法:
props将包含Dropdown组件的ID,但是由于您位于React组件中,因此请使用this.props.
return (
<select
id={this.props.id}
value={this.state.value}
onChange={this.handleChange}
disabled={disabled}
>
{dropdownOptions}
</select>
)
标签:reactjs,html-select,javascript 来源: https://codeday.me/bug/20191025/1931516.html