Open uniquejava opened 7 years ago
ES6 class | React.createClass() |
---|---|
getDefaultProps() | |
constructor(props) | getInitialState() |
componentWillMount() | componentWillMount() |
render() | render() |
componentDidMount() | componentDidMount() |
componentWillUnmount() | componentWillUnmount() |
简单版
const StarRating = ({starsSelected=0, totalStars=5, onRate=f=>f}) =>
<div className="star-rating">
{[...Array(totalStars)].map((n, i) =>
<Star key={i} selected={i<starsSelected} onClick={() => onRate(i+1)}/>
)}
<p>{starsSelected} of {totalStars} stars</p>
</div>
const ColorList = ({ colors=[] }) =>
<div className="color-list">
{(colors.length === 0) ?
<p>No Colors Listed. (Add a Color)</p> :
colors.map(color =>
<Color key={color.id} {...color} />
)
}
</div>
const Color = ({title,color,rating=0,onRemove=f=>f,onRate=f=>f}) =>
<section className="color">
<h1>{title}</h1>
<button onClick={onRemove}>X</button>
<div className="color"
style={{ backgroundColor: color }}>
</div>
<div>
<StarRating starsSelected={rating} onRate={onRate} />
</div>
</section>
带callback的版本.
...
npm install isomorphic-fetch --save
import { Component } from 'react'
import { render } from 'react-dom'
import fetch from 'isomorphic-fetch'
class CountryList extends Component {
constructor(props) {
super(props)
this.state = {
countryNames: [],
loading: false
}
}
componentDidMount() {
this.setState({loading: true})
fetch('https://restcountries.eu/rest/v1/all')
.then(response => response.json())
.then(json => json.map(country => country.name))
.then(countryNames =>
this.setState({countryNames, loading: false})
)
}
render() {
const { countryNames, loading } = this.state
return (loading) ?
<div>Loading Country Names...</div> :
(!countryNames.length) ?
<div>No country Names</div> :
<ul>
{countryNames.map(
(x,i) => <li key={i}>{x}</li>
)}
</ul>
}
}
class static properties
Refs
写法一
写法二: Stateless Functional Components (SFC)
写法三
用map代替for循环
完整实例:
super(props)的作用: Invoking super initializes the component instance, and React.Component decorates that instance with functionality that includes state management. After invoking super , we can initialize our component’s state variables.
Passing Data Back Up the Component Tree
bind的作用: This function(addColor) is bound to the component in the constructor, which means that it has access to this.state and this.setState
render method is invoked after every setState call