我正在尝试创建按钮数组,如下代码部分所示。我正在使用沙箱。我收到以下错误消息
代码:
import React from "react";
import ReactDOM from "react-dom";
import createReactClass from "create-react-class";
var arrButtons = [];
var buttonStyle = {
margin: '10px 10px 10px 0'
};
class ButtonClicks extends React.Component {
constructor(props) {
super(props);
this.onClickFunction = this.onClickFunction.bind(this);
}
onClickFunction() {
console.log("hello world from button: " + i);
};
render() {
return (
for (let i = 0; i < 10; i++) {
var button = <button
style={buttonStyle}
onClick={onClickFunction}>
p.name
</button>
arrButtons.push(button);
}
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<ButtonClicks />, rootElement);
export default ButtonClicks;
错误
/src/index.js: Unexpected token (21:4)
答案 0 :(得分:0)
您的方法是正确的。但! React的render
仅接受1个元素(该子元素可以具有所需数量的元素)。因此,您需要将这些按钮包装在div中。这是我将for
循环移到return
之外所做的唯一更改。
var arrButtons = [];
var buttonStyle = {
margin: '10px 10px 10px 0'
};
class ButtonClicks extends React.Component {
constructor(props) {
super(props);
this.onClick = this.onClick.bind(this);
}
onClick() {
console.log("hello world");
}
render() {
for (let i = 0; i < 10; i++) { //Moved your loop outside render()'s return
arrButtons.push(<button style={buttonStyle} onClick={this.onClick}>{i}</button>)
}
return (
<div>
{arrButtons} {/*Very important to wrap the buttons inside a div*/}
</div>
);
}
}
ReactDOM.render( <ButtonClicks/> , document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>