I'm attempting to build a Select dropdown and populate the input fields using a for loop.
import React, { Component } from 'react';
export default class Test extends Component {
render() {
let options = [];
for (let i=2; i < 20.5; i += 0.5){
options.push(<option value={i*60} key={i}>{i} hours</option>)
}
return (
<select>
{options}
</select>
)
}
}
The {i} hours
section causes an Uncaught TypeError: Cannot read property 'props' of undefined
error message. Changing it to a fixed string prevents the error.
I'm sure I'm missing something basic but I have no idea why this isn't working.
I'm attempting to build a Select dropdown and populate the input fields using a for loop.
import React, { Component } from 'react';
export default class Test extends Component {
render() {
let options = [];
for (let i=2; i < 20.5; i += 0.5){
options.push(<option value={i*60} key={i}>{i} hours</option>)
}
return (
<select>
{options}
</select>
)
}
}
The {i} hours
section causes an Uncaught TypeError: Cannot read property 'props' of undefined
error message. Changing it to a fixed string prevents the error.
I'm sure I'm missing something basic but I have no idea why this isn't working.
Share Improve this question asked Mar 1, 2016 at 5:16 user5633550user5633550 952 silver badges7 bronze badges 11- Works for me, usually the 'props' of undefined issue is with a this binding - is there more code somewhere? – user5004821 Commented Mar 1, 2016 at 5:20
- I thought it may have been some other code but I made this test ponent and render it directly to the page using the code below and it still occurs: ReactDOM.render(React.createElement(Test), document.querySelector('.react-container')); – user5633550 Commented Mar 1, 2016 at 5:25
- A Jsfiddle would help :) – Jeremy Rajan Commented Mar 1, 2016 at 5:26
- dont use React.createElement for es6 classes, just render the JSX ie ReactDom.render(<Test />, document.querySelector('.react-container')); createElement should only be used w/ ponents created with createClass – user5004821 Commented Mar 1, 2016 at 5:29
- Thanks for the tip. I only used it for the purposes of this test to pletely isolate this snippet from the rest of my code. – user5633550 Commented Mar 1, 2016 at 5:34
1 Answer
Reset to default 6Try this:
import React, { Component } from 'react';
export default class Test extends Component {
render() {
const options = [];
for (let i=2; i < 20.5; i += 0.5) options.push(i);
return (
<select>
{options.map(option => (
<option key={option} value={option*60}>
{option} hours
</option>
))}
</select>
)
}
}
or (in 2021) as a function ponent:
export default const Test = () => {
const options = [];
for (let i=2;i<20.5;i+=0.5) options.push(i);
return (
<select>
{options.map(option => (
<option key={option} value={option*60}>
{option} hours
</option>
))}
</select>
)
}
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744768199a4592592.html
评论列表(0条)