React之JSX

0.对于学习React,我们先来熟悉下JSX的语法,

下面的这些语法仅用于构建一个组件的标签模块,定义完成之后如果需要做演示,请附加以下代码:

ReactDOM.render(
    element1,
    document.body
);

即可完成标签的演示。

1.普通的标签

const element1 = <div>Hello JSX</div>;

2.带子标签的标签

const element2 = (
    <div>
        <h1>Hello Child1</h1>
        <span>Hello 2</span>
    </div>
);

3.1带变量的标签

const user = {
    name: 'qiumohanyu',
    age: 27,
    hobby: 'nothing',
    website: 'www.baidu.com'
};
const hasNav = true;
const element3_1 = (
    <div>
        <h1>{user.name}</h1>
        <span>{user.age}</span>
        <span>{user.hobby}</span>
        <a src={user.website}>主页</a>

        <div> {hasNav ? <nav>Nav</nav> : null}</div>
    </div>
);

3.2 内置函数的标签

function getItem() {
    return 'from function';
}

const element3_2 = <div>{getItem()}</div>;

4.1 带类名的标签 class=>className

const type = true;
const element4_1 = (
    <div>
        <div className="mycls">带class的标签</div>
        <span className={type?'class1':'class2'}>带判断逻辑的类名</span>
    </div>
);

4.2 带tabindex的标签 tabindex=>tabIndex

const element4_2 = <div tabIndex="0">带tabindex的标签</div>;

4.3 带for属性的label

const element4_3 = <label htmlFor="input1">User Name</label>;

5.1 属性

const MyComponent = React.createClass(
    {
        render: function() {
            return <div>My Component</div>
        }
    }
);
var x = "foo-value";
var y = "bar-value";
const element5_1 = <MyComponent foo={x} bar={y}/>;

5.2 属性延伸

var props = {};
props.foo = x;
props.bar = y;
const element5_2 = <MyComponent {...props} />;
//需要覆盖时
const element5_3 = <MyComponent {...props} foo={'new-value'}/>;

6 style属性

var mystyles = {
    color: 'red',
    border: '1px solid #000'
};
const element6 = <div style={mystyles}></div>;

7 HTML转义

var innerHtml = '<span> my span label</span>';
var toDiv = { __html: innerHtml };
const element7 = (
    <div dangerouslySetInnerHTML={toDiv}></div>
);

8 自定义HTML属性

const element8=(
    <div data-id="can render" ride="can not be render"></div>
);

 

posted @ 2016-10-22 22:21  秋末寒雨  阅读(297)  评论(0编辑  收藏  举报