jsx 反应:导入JSON数据

如何以各种方式将JSON导入React项目。我们可以提取整个JSON文件 - 或者 - 只提取所需的特定密钥内容。

Example.jsx
import React, { Component } from "react";

// Import all data from JSON as an object 'data'

import * as data from "data.json" // this option is identical to the next line
import data from "data.json";

class export default Example extends Component {
  render() {
    var example = data.key;
    return (
      <div>{data.key}</div>;
      <div>{example}</div>;
    );
  }
}


// import specific key contents as a new object 'data'

import { exampleKey } as data from "data.json"

class export default Example extends Component {
  render() {
    var example = data.key;
    return (
      <div>{data.key}</div>;
      <div>{example}</div>;
    );
  }
}


// access key contents directly - use sparingly

import { exampleKey } from "data.json";

class export default Example extends Component {
  render() {
    var example = exampleKey.key; // won't work
    return (
      <div>{exampleKey.key}</div>;
    );
  }
}

jsx 道具ile风格gönderipalma

bunla styleveriikışıyapılır

propsToStyle.js
getStyle = (): ViewStyle => {
        const style = [StyleSheet.flatten(styles.cardImage, this.props.width)];
        style.push({ width: this.props.width});
        return StyleSheet.flatten(style);
    };

jsx 基本数

count.js
// JSX - JavaScript XML

var app ={
    title: 'Focus App',
    subtitle: 'The TODO App',
    options: ['One', 'Two'] 
}

var template = (
    <div>
        <h1>{app.title}</h1>
        {app.subtitle && <p>{app.subtitle}</p>}
        <p>{app.options.length > 0 ? 'Here are your options' : 'No options' }</p>
        <p></p>
        <ol> 
            <li>Item one</li>
            <li>Item two</li>
        </ol>

    </div>
);

let count = 0;

const addOne = () => {
    count++;
    renderCounterApp();
};
const minusOne = () => {
    count--;
    renderCounterApp();
};
const reset = () => {
    count = 0;
    renderCounterApp();
};

var appRoot  = document.getElementById('app');

const renderCounterApp = () => {
    const templateTwo = (
        <div className="container">
            <br></br>
            <br></br>
            <br></br>
                <h1>Count : {count}</h1>
                <button id="my-id" className="button btn btn-outline-danger btn-sm" onClick={addOne} >&nbsp;&nbsp;&nbsp;&nbsp; +1 &nbsp;&nbsp;&nbsp;&nbsp;</button> &nbsp;&nbsp;
                <button id="my-id" className="button btn btn-outline-danger btn-sm" onClick={minusOne} >&nbsp;&nbsp;&nbsp;&nbsp; -1 &nbsp;&nbsp;&nbsp;&nbsp;</button>  <br></br><br></br>
                <button id="my-id" className="button btn btn-outline-danger btn-sm" onClick={reset} >&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Reset
                &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;</button>
        </div>
    );

    ReactDOM.render(templateTwo, appRoot);

};
  renderCounterApp();

jsx 状态语法

state-syntax
class TodayImFeeling extends React.Component {
  constructor(props) {
    super(props);
    this.state = { mood: 'decent' };
  }

  render() {
    return (
      <h1>
        I'm feeling {this.state.mood}!
      </h1>
    );
  }
}

//BINDING:
class Random extends React.Component {
  constructor(props) {
    super(props);
    this.state = { color: [200, 15, 30] }
    this.handleClick = this.handleClick.bind(this);
  }
  

jsx ReactDOM.Render

react-dom-render
ReactDOM.render(
  <RedPanda />,
  document.getElementById('app')
);

jsx 来自“JSX II”课程的“Authorizaton Form”项目

来自“JSX II”课程的“Authorizaton Form”项目

gistfile1.txt
import React from 'react';
import ReactDOM from 'react-dom';

class Contact extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      password: 'swordfish',
      authorized: false
    };
    this.authorize = this.authorize.bind(this);
  }

  authorize(e) {
    const password = e.target.querySelector(
      'input[type="password"]').value;
    const auth = password == this.state.password;
    this.setState({
      authorized: auth
    });
  }

  render() {
    let login = (
      <form action="#" onSubmit="authorize()">
        <input
          type="password"
          placeholder="password" />
        <input type="submit"/>        
      </form>
    );

    const contactInfo = (
      <ul>
        <li>
          client@example.com
        </li>
        <li>
          555.555.5555
        </li>
      </ul>      
    );
        
    if (!this.state.authorized) {
      return (
        <div id="authorization">
          <h1>Enter the Password</h1>
          {login}
        </div>
      );
    } else {
      return (
        <div id="authorization">
          <h1>Contact</h1>
          {contactInfo}
        </div>
      );
    }
  }
}

ReactDOM.render(
  <Contact />, 
  document.getElementById('app')
);

jsx 反应路由

反应路由

header.js
import React, { Component } from 'react';
import {Link} from 'react-router-dom';

export default class Header extends Component {
  render () {
    return (
      <div>
        <div><Link to="/a">点击A</Link></div>
        <div><Link to="/a/aa">点击AA</Link></div>
        <div><Link to="/b">点击B</Link></div>
        <div><Link to="/c">点击C</Link></div>
      </div>
    )
  }
}
app.js
import React, { Component } from 'react'
import { BrowserRouter as Router, Switch, Route, Redirect } from 'react-router-dom';
// withRouter 才有history对象   this.props.history.push("/"); 跳转路由
// export default withRouter(Header);
import './App.css'
import Hearder from '../Header';
import ModuleA from '../ModuleA';
import ModuleAA from '../ModuleAA';
import ModuleB from '../ModuleB';
import ModuleC from '../ModuleC';

class App extends Component {
  render() {
    return (
      <Router>
        <div>
          <Hearder />
          <Switch>
            {/* exact   "/a"之后不允许再加 "/*", 除非有子路由
                strict  "/a"之后不能再加 "/" 
            */}
            <Route exact strict path='/a' component={ModuleA}/>
            <Route path='/a/aa' component={ModuleAA}/>
            <Route path='/b' component={ModuleB}/>
            <Route path='/c' component={ModuleC}/>
            <Redirect from="/" to="/a" />
          </Switch>
          <div>我是footer</div>
        </div>
      </Router>
    );
  }
}

export default App;

jsx 反应的警报组件

反应的警报组件

Modal组件
// 定义Modal组件
import React, { Component, PropTypes } from 'react';
import classnames from 'classnames'
class Dialog extends Component {
  constructor(props) {
    super();
    this.state = {
      // 显示状态
      visible: false,
      // 标题
      title: "",
      // 内容
      children: "",
      // 取消事件
      onCancel: () => {},
      // 确认事件
      onOk: () => {},
      // 底部按扭方案
      footer: [
        "取消", "确认"
      ]
    }
  }
  componentWillMount() {
    this.setProps();
  }
  componentWillReceiveProps(nextProps) {
    // 组件更新后获取最新props
    this.setProps(nextProps);
  }
  setProps(props = this.props) {
    // 扩展运算符props中一一解析到state中
    this.setState({
      ...props
    })
  }
  /**
   * 隐藏对话框
   * @return {[type]} [description]
   */
  hideModal() {
    this.setState({
      visible: false
    })
  }
  /**
   * 确认事件
   * @return {[type]} [description]
   */
  handleOkClick() {
    // 执行Ok方法,如果有传入的ok方法,则执行
    this.hideModal();
    this.props.onOk && this.props.onOk();
  }
  /**
   * 取消事件
   * @return {[type]} [description]
   */
  handleCancelClick() {
    this.hideModal();
    this.props.onCancel && this.props.onCancel();
  }
  getMaskElement() {
    // 获取遮罩渲染元素
    let maskElement;
    if(this.state.visible) {
      maskElement = (
        <div>
          {this.state.visible ? <div className="ui-modal-mask"  style={styles} /> : null}
        </div>
      )
    }
    return maskElement;
  }
  getDialogElement() {
    // 获取弹窗元素
    let DialogElement;
    let { title } = this.state;
    let uibody = classnames(
      'ui-modal-body',
      {
        'no-header' : !title
      }
    )
    if(this.state.visible) {
      DialogElement = (
        <div className="ui-modal-wrap">
          <div className="ui-modal">
            {
              title ?  <div className="ui-modal-header">{ title }</div> : null
            }
            <div className={uibody}>
              {this.props.children}
            </div>
            {
              (this.state.footer.length >= 2) ? (
                <div className="ui-modal-footer">
                  <a href="javascript:" className="ui-modal-button" onClick={this.handleCancelClick.bind(this)}>{this.state.footer[0]}</a>
                  <a href="javascript:" className="ui-modal-button" onClick={this.handleOkClick.bind(this)}>{this.state.footer[1]}</a>
                </div>
              ) : (
                <div className="ui-modal-footer">
                  <a href="javascript:" className="ui-modal-button ui-modal-button1" onClick={this.handleOkClick.bind(this)}>{this.state.footer[0]}</a>
                </div>
              )
            }
          </div>
        </div>
      );
    }
    return DialogElement;
  }
  render() {
    return (
      <div>
        {this.getMaskElement()}
        {this.getDialogElement.call(this)}
      </div>
    );
  }
};
Dialog.propTypes = {
  visible: PropTypes.bool,
  title: PropTypes.string,
  onCancel: PropTypes.func,
  onOk: PropTypes.func,
  footer: PropTypes.array
}
export default Dialog;
alert组件

// 定义 alert 组件
import React from 'react';
import ReactDOM, { render } from 'react-dom';
import Modal from './modal';
export default function (...args) {
  const title = args[0];
  const content = args[1];
  const onOk = args[2] || function(){};
  const footer = args[3] || ["取消", "确认"];
    
  // 新建div 用于render结果渲染在div中
  let div = document.createElement('div');
  document.body.appendChild(div);
  function close() {
    // 移除组件和div
    ReactDOM.unmountComponentAtNode(div);
    div.parentNode.removeChild(div);
  }
  function handleOk() {
    // 执行外部传来的OK() 调用close关闭组件
    onOk();
    close();
  }
  render(
    <Modal
      visible
      title={title}
      onCancel={close}
      onOk={handleOk}
      footer={footer}
    >
      <div style={{ zoom: 1, overflow: 'hidden' }}>{content}</div>
  </Modal>, div);
};
调用
 // 调用
Alert(``, `你的手机号码还未通过验证,请先验证手机号码后再申请报名`, () => {
    go(url.player.phone, false);
}, ["取消", "验证手机号"]);

jsx ReactJs - 箭头功能

如何在es6中编写箭头函数

reactjs arrow functions
// FUNCTION EXPRESSION
function (){...}

// ARROW FUNCTION EXPRESSION
() => {..}

// EXAMPLES 
//allowed
item => {...} 
(item) => {...}
(item, key) => {...}

// not allowed
item, key => {...}

// MORE EXAMPLES
const listItems = list.map(function(item){
  return (
    <div key={item.objectID}>
        <a href='{item.url}'>{item.title}</a>
          <div>{item.author}</div>
          <div>{item.num_comments}</div>
          <div>{item.points}</div>
    </div>
  );
});

const listItems = list.map(item => 
  <div key={item.objectID}>
    <a href='{item.url}'>{item.title}</a>
    <div>{item.author}</div>
    <div>{item.num_comments}</div>
    <div>{item.points}</div>
  </div>
);

// FUNCTION BODY
let func = x => x * x; // concise body syntax, implied "return"

let func = (x, y) => { return x + y; }; // with block body, explicit return needed

jsx ReactJs - 关键

“key”是在创建元素列表时需要包含的特殊字符串属性。 <br/> <br/>键帮助React识别哪些项目已更改,已添加或已删除。应该为数组中的元素赋予键,以便为元素提供稳定的标识:<br/> <br/>选择键的最佳方法是使用一个字符串,该字符串在其兄弟中唯一标识列表项。大多数情况下,您会使用数据中的ID作为键:

reactJs key
/*KEYS */

const listItem = list.map(function(item){
  return (
      <div key={item.objectID}> 
          <span>
            <a href="{item.url}">{item.title}</a>
          </span>
          <span>Author: {item.author}</span>
          <span>Comments: {item.num_comments}</span>
          <span>Points: {item.points}</span>
      </div>
  );
});