1. 帶有自己名字的HelloMessage組件,名字通過props傳遞。
import React from 'react'
import ReactDOM from 'react-dom'
function ShowMsg({name}) {
return (
<h1>Hello, {name}</h1>
)
}
const Hello = React.createClass({
getInitialState() {
return {
msg: 'Long'
}
},
handleInput(e) {
this.setState({msg: e.target.value})
},
render() {
return (
<div>
<input
value={this.state.msg}
onChange={this.handleInput} />
<ShowMsg name={this.state.msg} />
</div>
)
}
})
ReactDOM.render(
<Hello/>,
document.getElementById('container')
)
2. 一個背景色為綠色的盒子耸序,3秒后顏色變?yōu)榧t色忍些。
index.css
* {
margin: 0; padding:0;
}
.box {
width: 200px; height:200px;
margin: -100px -100px; position: fixed; top: 50%; left: 50%;
}
index.js
import React from 'react'
import ReactDOM from 'react-dom'
import './index.css'
class Box extends React.Component {
constructor(props) {
super(props)
this.state = {c: 'green'}
this.change = this.change.bind(this)
}
componentDidMount() {
setTimeout(
() => this.change(),
3000
)
}
change() {
this.setState({
c: 'red'
})
}
render() {
return (
<div className="box" style={this.state.c === 'green' ? {background:'green'} : {background:'red'}}></div>
)
}
}
ReactDOM.render(
<Box />,
document.getElementById('root')
)