React入门

sandbox在线演示

import React from "react"; import ReactDOM from "react-dom"; import "./styles.css"; function App() { return (Hello CodeSandbox Start editing to see some magic happen!); }const rootElement = document.getElementById("root"); ReactDOM.render(, rootElement);

hello world
ReactDOM.render( hello, wolrd!, document.getElementById('root') )

嵌入表达式
const name = 'gjyao' const element = Hello, {name}function formatName(user){ return user.firstName + ' ' + user.lastName } const user = { firstName: 'Harper', lastName: 'Perez' }const element = (Hello, {formatName(user)}!) ReactDOM.render( element, document.getElementById('root') )

更新已渲染的元素
function tick(){ const element = (Hello, world It is {new Date().toLocaleTimeString()}.) ReactDOM.render(element, document.getElementById('root')) } setInterval(tick, 1000)

函数组件与class组件
function Welcome(pros) { return Hello, {pros.name}; }class Welcome extends React.Component { render() { return Hello, {this.props.name} } }

【React入门】以上两种组件都是等效的
const element = ; ReactDOM.render( element, document.getElementById('root') );

组合组件
function App() { return ( ) }ReactDOM.render(, document.getElementById("root"));

State
class Clock extends React.Component{// Class组件应始终使用props参数来调用父类的构造函数 constructor(props){ //将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 (Hello, wolrd! 现在是{this.state.date.toLocaleTimeString()}。) } }

每个组件相互独立
function App(){ return( ) }ReactDOM.render(, document.getElementById("root"));

事件处理
function ActionLink() { function handleClick(e) { //e是一个合成事件 e.preventDefault() console.log("the link was clicked") }return (Click Me) }ReactDOM.render(, document.getElementById("root"))class Toggle extends React.Component{ constructor(props){ super(props) this.state = {isToggle: true}// 为了在回调中使用 `this`,这个绑定是必不可少的 this.handleClick = this.handleClick.bind(this) }handleClick() { this.setState(state=>({ isToggle: !state.isToggle })) }render(){ return ( ) } }class Toggle extends React.Component{ constructor(props){ super(props) this.state = {isToggle: true} }//public class fields 语法, //此语法确保 `handleClick` 内的 `this` 已被绑定。 handleClick = ()=> { this.setState(state=>({ isToggle: !state.isToggle })) }render(){ return ( ) } } ReactDOM.render(, document.getElementById("root"))

条件渲染
function LoginButton(props) { return ( ) }function LogoutButton(props) { return ( ) }function UserGreeting(props) { return Welcome back!; }function GuestGreeting(props) { return Please sign up.; }function Greeting(props) { const isLoggedIn = props.isLoggedIn; if (isLoggedIn) { return ; } return ; }

有状态组件
class LoginControl extends React.Component{ constructor(props){ super(props) this.state = {isLoggedIn: false} }handleLoginClick = ()=>{ this.setState({isLoggedIn: true}) }handleLogoutClick = ()=>{ this.setState({isLoggedIn: false}) }render(){ const isLoggedIn = this.state.isLoggedIn let buttonif (isLoggedIn){ button = } else { button = }return ( {button}) } }ReactDOM.render(, document.getElementById("root"))

与运算符
function Mailbox(props) { const unreadMessages = props.unreadMessages; return (Hello! {unreadMessages.length > 0 &&You have {unreadMessages.length} unread messages.}); }const messages = ['React', 'Re: React', 'Re:Re: React']; ReactDOM.render( , document.getElementById('root') );

阻止渲染
function WarningBanner(props) { if (!props.warn) { return null; }return (Warning!); }class Page extends React.Component { constructor(props) { super(props); this.state = {showWarning: true}; this.handleToggleClick = this.handleToggleClick.bind(this); }handleToggleClick() { this.setState(state => ({ showWarning: !state.showWarning })); }render() { return ( ); } }ReactDOM.render(, document.getElementById('root') );

基础列表组件
function NuberList(props) { const numbers = props.numbers const listItems = numbers.map(number =>
  • {number}
  • ) return (
      {listItems}
    ) }const number = [1, 2, 3, 4, 5] ReactDOM.render( , document.getElementById('root') );

    受控组件
    class NameForm extends React.Component { constructor(props) { super(props) this.state = {value: ''} }handleChange = (event) => { this.setState({value: event.target.value}) console.log(this.state) }handleSubmit = (event) => { alert('提交的名字: ' + this.state.value) event.preventDefault() }render() { return (
    ) } } ReactDOM.render( , document.getElementById('root') );

    处理多个输入
    class Reservationextends React.Component { constructor(props) { super(props) this.state = { isGoing: true, numberOfGuests: 2 } }handleInputChange= (event) => { const target = event.target const value = https://www.it610.com/article/target.type ==='checkbox' ? target.checked : target.value const name = target.name//使用了 ES6计算属性名称的语法更新给定输入名称对应的 state 值 this.setState({ [name]: value })}render() { return (

    ) } } ReactDOM.render( , document.getElementById('root') );

    状态提升
    const scaleNames = { c: "Celsius", f: "Fahrenheit" }; function toCelsius(fahrenheit) { return ((fahrenheit - 32) * 5) / 9; }function toFahrenheit(celsius) { return (celsius * 9) / 5 + 32; }function tryConvert(temperature, convert) { const input = parseFloat(temperature); if (Number.isNaN(input)) { return ""; } const output = convert(input); const rounded = Math.round(output * 1000) / 1000; return rounded.toString(); }class TemperatureInput extends React.Component { constructor(props) { super(props); this.state = { temperature: "" }; }handleChange = e => { this.props.onTemperatureChange(e.target.value); }; render() { const temperature = this.props.temperature; const scale = this.props.scale; return (
    Enter temperature in {scaleNames[scale]}:
    ); } }class Calculator extends React.Component { constructor(props) { super(props); this.state = { temperature: "", scale: "c" }; }handleCelsiusChange = temperature => { this.setState({ scale: "c", temperature }); }; handleFahrenheitChange = temperature => { this.setState({ scale: "f", temperature }); }; render() { const scale = this.state.scale; const temperature = this.state.temperature; const celsius = scale === "f" ? tryConvert(temperature, toCelsius) : temperature; const fahrenheit = scale === "c" ? tryConvert(temperature, toFahrenheit) : temperature; return (); } }ReactDOM.render(, document.getElementById("root"));

      推荐阅读