美文网首页
4.2 Rendering a Component 渲染一个组件

4.2 Rendering a Component 渲染一个组件

作者: 人头原子弹 | 来源:发表于2017-04-17 21:46 被阅读0次

    Previously, we only encountered React elements that represent DOM tags:

    以前,我们只会遇到表示DOM标签的React元素。

    const element =<div /> ;

    However, elements can also represent user-defined components:

    同样,元素也能够表示用户自定义组件:

    const element = <Welcome name="Sara" />;

    When React sees an element representing a user-defined component, it passes JSX attributes to this component as a single object. We call this object "props".

    当我们看见一个元素表示用户自定义组件,它把JSX属性作为一个单独对象传递给这个组件。我们称这个对象为“props”。

    For example, this code renders "Hello, Sara" on the page:

    举个例子,这段代码在页面上渲染出“Hello, Sara”:

    function Welcome(props) {
    return <h1>Hello, {props.name}</h1>;
    }
    const element = <Welcome name="Sara" />;
    ReactDOM.render(
    element,
    document.getElementById('root')
    );

    Try it on CodePen.

    在CodePen中尝试。

    Let's recap what happens in this example:

    让我们回顾一下刚刚的事例都做了什么:

    1.We call ReactDOM.render() with the <Welcome name="Sara" /> element.

    1.我们调用ReactDOM.render()来渲染元素

    2.React calls the Welcome component with {name: 'Sara'} as the props.

    2.React 调用一个使用{name: 'Sara'}做为props的Welcome组件。

    3.Our Welcome component returns a <h1>Hello, Sara</h1>element as the result.

    3.我们的welcome组件返回<h1>Hello, Sara</h1>元素做为结果。

    4.React DOM efficiently updates the DOM to match<h1>Hello, Sara</h1>.

    4.React DOM 及时有效的更新DOM去匹配<h1>Hello, Sara</h1>。

    Caveat:
    Always start component names with a capital letter.
    For example, <div />represents a DOM tag, but<Welcome />represents a component and requires Welcome to be in scope.
    警告:
    通常组件名称的开头是个大写字母。

    例如,<div />表示一个DOM标签,但是<Welcome />表示一个组件并且要求Welcome在作用域内。

    相关文章

      网友评论

          本文标题:4.2 Rendering a Component 渲染一个组件

          本文链接:https://www.haomeiwen.com/subject/iieoattx.html