1、一个demo(https://www.reactjscn.com/docs/state-and-lifecycle.html)
class Clock extends React.Component {
constructor(props) {
super(props);
this.state = {date: new Date()};
} componentDidMount() {
this.timerID = setInterval(
() => this.tick(),
1000
);
} componentWillUnmount() {
clearInterval(this.timerID);
} tick() {
this.setState({
date: new Date()
});
} render() {
return (
<div>
<h1>Hello, world!</h1>
<h2>It is {this.state.date.toLocaleTimeString()}.</h2>
</div>
);
}
} ReactDOM.render(
<Clock />,
document.getElementById('root')
);
2、demo: 兄弟组件之间通信,使用到生命周期钩子componentWillReceiveProps
项目结构:
demo效果:“搜索组件”传递keyword参数给父组件,然后父组件将keyword参数传递给“显示子组件”
App.jsx
import React from 'react'
import UserSearch from '../user-search/UserSearch.jsx'
import UserList from '../user-list/UserList.jsx' export default class App extends React.Component {
constructor(props) {
super(props)
this.state = {
keyword: ''
} this.setKeyword = this.setKeyword.bind(this)
} setKeyword(keyword) {
console.log(`App组件setKeyword被调用, keyword=${keyword}`)
this.setState({ keyword })
} render() {
return (
<div>
<UserSearch setKeyword={this.setKeyword} />
<UserList keyword={this.state.keyword} />
</div>
)
}
}
UserSearch.jsx
import React from 'react'
import PropTypes from 'prop-types' export default class UserSearch extends React.Component {
state = {
keyword: ''
} static propTypes = {
setKeyword: PropTypes.func.isRequired
} render() {
const { keyword} = this.state
return (
<div>
<h3>搜索用户</h3>
<input type="text" placeholder="请输入搜索关键字" name="keyword" value={keyword} onChange={(e) => this.keywordInputOnChangeHandler(e)} />
<input type="button" value="开始搜索" onClick={() => this.searchClickHandler()} />
</div>
)
} keywordInputOnChangeHandler = (e) => {
const keyword = e.target.value
this.setState({ keyword })
} searchClickHandler = () => {
const { keyword } = this.state
console.log(`keyword.trim()=${keyword.trim()}`)
if (!keyword.trim()) return
this.props.setKeyword(keyword)
}
}
UserList.jsx
import React from 'react'
import PropTypes from 'prop-types'
import Axios from 'axios' export default class UserList extends React.Component {
state = {
userList: []
} componentWillReceiveProps(newProps) {
const { keyword } = newProps
Axios.get(`http://localhost:4000/react-db-crud/user/search?keyword=${keyword}`)
.then(res => {
if (res.data.code == 0) {
const userList = res.data.data
console.log(`userList=${JSON.stringify(userList)}`)
this.setState({ userList })
}
})
} render() {
return (
<div>
{
this.state.userList.map(user => <p>{user.id + "--" + user.name + "--" + user.age}</p>)
}
</div>
)
}
} UserList.propTypes = {
keyword: PropTypes.string.isRequired
}