class Lamp extends React.component {
constructor(){
super();
this.state = {
active: false
};
}
toggleActive() {
this.setState({ active: !this.state.active });
}
render() {
return (
<div
style={{ backgroundColor: this.state.active ?
this.props.color : "" }}>lampada
<button onclick={() => this.toggleActive()}>on/off</button>
</div>
);
}
}
React.render(<Lamp color="green" />, document.body);
打开index.html时,我什么也看不到,chrome的调试告诉我:“未封闭的正则表达式”
最佳答案
您应该改为使用react-dom
。ReactDOM.render(<Lamp color="green" />, document.body)
class Lamp extends React.Component {
constructor() {
super()
this.state = {
active: false,
}
this.toggleActive = this.toggleActive.bind(this)
}
toggleActive() {
this.setState({ active: !this.state.active })
}
render() {
return (
<div
style={{ backgroundColor: this.state.active ? 'green' : 'red' }}
>
lampada
<button onClick={this.toggleActive}>on/off</button>
</div>
)
}
}
ReactDOM.render(
<Lamp />,
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>