FCC React takeaway

/* React code samples from FreeCodeCamp */

// JSX element needs to be wrapped in one element.
const JSX = (
    <div>
        {/* class is replaced with className */}
        <p className="myClass">Paragraph One</p>
        {/* every element can be self-closing in JSX,  */}
        {/* always include forward slash */}
        <div />
    </div>
);

//Stateless Functional Component
const ChildComponent = (props) => {
    return (
        <div>
            {/* access props by 'props', events are camelCase */}
            <button onClick={props.method}>{props.data}</button>
        </div>
    );
};

//React Component
class ParentComponent extends React.Component {
    constructor(props) {
        super(props);
        this.state = { // initialize state
            name: 'Jack',
            itemCount: 0,
            input: '',
            submit: ''
        };
        // bind handler to this when using class method
        this.handleClick = this.handleClick.bind(this);
        this.handleChange = this.handleChange.bind(this);
        this.handleSubmit = this.handleSubmit.bind(this);
    }
    // event handler
    handleClick() {
        // use this.setState() to update state
        // avoid assigning state directly
        this.setState({
            itemCount: this.state.itemCount + 1
        });
    }
    handleChange(event) { // update state from input
        this.setState({
            input: event.target.value
        });
    }
    handleSubmit(event) {
        // prevent default refresh or loading another page
        event.preventDefault();
        this.setState({
            submit: this.state.input,
            input: ''
        });
    }

    //lifecycle methods
    // run before the first time render() is called
    componentWillMount()
    // run after mounted to DOM
    // API calls to server and document|window event handler go here
    componentDidMount()
    // incoming props as 'nextProps', current props is 'this.props'
    componentWillReceiveProps(nextProps)
    // decide whether to update or not, return a boolean
    shouldComponentUpdate(nextProps, nextState)
    // run before update
    componentWillUpdate()
    // run after update
    componentDidUpdate()
    // clean up, such as removeEventListener()
    componentWillUnmount()

    // render to DOM
    render() {
        // plain JS code goes here
        let name = this.state.name;
        let styles = { // inline style
            color: 'purple',
            fontSize: 40,
            border: '2px solid purple'
        }
        if (this.state.condition) { // control style with state
            styles = {};
        }
        // create list item from array
        const items = this.state.toDoList.map((
            element, index) => (<li key={index}>{element}</li>)
        );

        // JSX element to render
        return (
            <div>
                <h1>{this.props.data}</h1> {/* access props by 'this.props' */}
                <p>{this.state.name}</p> {/* access state by 'this.state' */}
                <p>{name}</p> {/* access local variable */}

                {/* add submit event handler */}
                <form onSubmit={this.handleSubmit}>
                    {/* add click event handler */}
                    <button onClick={this.handleClick}>Click Me</button>
                    {/* info input -> state -> input */}
                    <input
                        type='text'
                        value={this.state.input}
                        onChange={this.handleChange}
                    ></input>
                    <button type='submit'>Submit!</button>
                </form>

                {/* pass props to child */}
                <ChildComponent
                    data={this.state.name}
                    method={this.handleChange}
                />

                {/* inline style, note the double braces and camelCase */}
                <span style={{ color: "red", fontSize: 72 }}>abc</span>
                {/* or separate style in a variable */}
                <span style={styles}>abc</span>

                {/* condition && element, render element or nothing */}
                {this.state.display && <h1>Displayed!</h1>}
                {/* ternary to choose between two elements */}
                {this.state.userAge < 18 ?
                    <p>You can not pass</p> :
                    <p>You are free to go</p>
                }
            </div>
        );
    }
};

//default props
MyComponent.defaultProps = { items: 0 };

//props types check
// Other type: PropTypes.bool, .number, .string, etc.
import React, { PropTypes } from 'react';
MyComponent.propTypes = { handleClick: PropTypes.func.isRequired }

//render JSX element in the container(#root)
ReactDOM.render(JSX, document.getElementById('root'))

//render Component in the container(#root)
ReactDOM.render(<App />, document.getElementById('root'))

//render React on the server for search engine and loading speed
ReactDOMServer.renderToString(<App />);



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值