The document serves as an introduction to React, outlining its declarative programming style and component-based architecture for building user interfaces. It discusses the concepts of state, props, and component lifecycle, providing examples of how to create components and manage data flow in a React application. Additionally, it emphasizes the importance of the virtual DOM and uni-directional data flow in efficient UI rendering.
props ! passed in fromparent ! <MyComp foo="bar" /> this.props read-only within ! can be defaulted & validated state ! created within component ! getInitialState this.state to read this.setState() to update
22.
var MyComponent =React.createClass({ ! propTypes: {}, getDefaultProps: function () {}, getInitialState: function () {}, ! componentWillMount: function () {}, componentWillUnmount: function () {}, ... render: function () { // only read props & state -> return UI }, });
23.
var MyComponent =React.createClass({ ! iGotClicked: function () {...}, ! render: function () { return <div onClick={this.iGotClicked}>Click</div>; }, }); Or a parent’s method passed in via props
var Table =React.createClass({ getInitialState: function () { var data = []; for (var r = 0; r < this.props.rows; r++) { data[r] = []; for (var c = 0; c < this.props.columns; c++) { data[r][c] = 0; } } return {data: data}; }, render: function () {return <table>...</table>;} }); ! React.render(<Table columns={4} rows={3} />, ...
37.
var Row =React.createClass({ render: function () { return <tr>{this.props.children}</tr>; } }); ! var Total = React.createClass({ render: function () { return <th>{this.props.value}</th>; } });
38.
var Cell =React.createClass({ onChange: function (e) { this.props.onChange( this.props.row, this.props.column, parseInt(e.target.value) || 0 ); }, render: function () { return (<td> <input type="number" value={this.props.value} onChange={this.onChange} /> </td>); }, });
39.
var Table =React.createClass({ onCellChange: function(row, column, value) { this.state.data[row][column] = value; this.setState({data: this.state.data}); }, ! render: function() { // for rows & columns, append <Row>s containing // <Cell row={r} column={c} // value={this.state.data[r][c]} // onChange={this.onCellChange} /> // // also append to each row and in a final row: // <Total value={total} /> }, ...