import React from "react";
const Option = ({ ops }) => {
return (
<React.Fragment>
{ops.map((op, index) => {
return (
<option key={index} value={op.value} data-value={op["data-value"]}>
{op.value}
</option>
);
})}
</React.Fragment>
);
};
const Select = ({ children, onChange }) => {
return <select onChange={onChange}>{children}</select>;
};
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
value: null,
custom_attribute: null
};
}
onChange = e => {
const customAttribute = e.target[e.target.selectedIndex].dataset.value;
const value = e.target.value;
this.setState({
value: value,
custom_attribute: customAttribute
});
};
render() {
const options = [
{ value: "one", "data-value": "1" },
{ value: "two", "data-value": "2" },
{ value: "three", "data-value": "3" }
];
return (
<React.Fragment>
<Select onChange={this.onChange}>
<Option ops={options} />
</Select>
<h1>{`value:${this.state.value}`}</h1>
<h1>{`custom attribute:${this.state.custom_attribute}`}</h1>
</React.Fragment>
);
}
}
export default App;
hookを使用した例
import React, { useState } from 'react';
const Option = ({ops}) => {
return(
<React.Fragment>
{ops.map((op, index) => {
return <option key={index} value={op.value} data-value={op['data-value']}>{op.value}</option>
})}
</React.Fragment>
);
};
const Select = ({children, onChange}) => {
return(
<select onChange={onChange}>
{children}
</select>
)
};
const App = () => {
const [customAttribute, setCustomAttribute] = useState(null);
const [value, setValue] = useState(null);
const options = [
{value: "one", 'data-value': '1'},
{value: "two", 'data-value': '2'},
{value: "three", 'data-value': '3'},
];
const onChange = (e) => {
const customAttribute = e.target[e.target.selectedIndex].dataset.value;
const value = e.target.value;
setValue(value);
setCustomAttribute(customAttribute);
};
return(
<div>
<Select onChange={onChange}>
<Option ops={options}/>
</Select>
<h1>{`value:${value}`}</h1>
<h1>{`custom attribute:${customAttribute}`}</h1>
</div>
)
};