Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

JSX in Depth #12

Open
Alexis374 opened this issue Aug 22, 2016 · 0 comments
Open

JSX in Depth #12

Alexis374 opened this issue Aug 22, 2016 · 0 comments

Comments

@Alexis374
Copy link
Owner

JSX in Depth

本文为我读《ReactJS by Example》英文书第二章的总结

  • why jsx?
    • jsx 代码可读性更高,更简单
  • 在jsx中,原生html标签为小写,自定义的React组件开头要大写
  • JSX是XML-like的,这意味着必须要有结束标签,不管是<App />还是<App></App>
  • js表达式,用{}包裹起来的表达式,大体上分为两类,一类是普通的js语句,用于求值,比较等;另一类用在JSX语句的内部,通常值是多个React元素组成的列表
render(){
    return (<tbody>
        {
            {/* 下面表达式返回的是由Row元素组成的数组。这种表达式中插入注释也和普通的表达式不同  */}   
            this.props.changeSets.map((changeSet,index)=>{
                return <Row changeSet={changeSet} key={index} />
            })
        }        
    </tbody>)
    }
  • {this.props.children}的用法:
    {this.props.children}可以把一个元素包装成另一个元素而不改变其功能。比如,
    原来的元素是
class App extends Component{
    render(){
        return (
            <table>
                <A a={this.props.a} />
                <B b={this.props.b} />
            </table>
        )
    }
}
//将 table元素包装成自定义元素 RecentChangesTable:
class RecentChangesTable extends Component{
    render(){
        return (<table>
            {this.props.children}
        </table>
    }
}
class App extends Component{
    render(){
        return (
            <RecentChangesTabl>
                <A a={this.props.a} />
                <B b={this.props.b} />
            </RecentChangesTable>  

        )
    }
}
  • spread attibute:
var props={
    a:'123',
    b:'456'
}
//传递给组件时:
ReactDOM.render(<App {...props}/>,document.getElementById('app'))
  • style: style,class需要设置在真实的DOM元素上。注意是className
    • <table style={{backgroundColor:'#fff',}}>
    • <table className = 'recentChangesTable'>
  • 设置不在html规范上的属性最终不会渲染,data-除外。
  • 转义特殊字符串:
    <div>you &amp; me </div> // 直接写在元素里的不会转义 ,输出you & me
    var str = 'you &amp; me' // 输出 you &amp; me 
    <div>{str} </div> //当做变量传进来的会转义

    // 避免转义的方法:
    1. 用一个数组 <div> {['first', <span>&amp;</span>, 'second']} </div>
    2. <div dangerouslySetInnerHTML={{__html: 'Mike &amp; Shawn'}} />
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant