无论如何有条件地渲染一次或多次React组件?

时间:2017-08-17 19:21:36

标签: javascript reactjs

此问题与以下内容不同: React:如何在页面中渲染两次组件?

请务必阅读问题!!!!!!!!

这个问题适用于超过一页的条件!另一个问题是固定的时间。

我在ReactmyComponent.js中有一个组件构建

ReactDOM.render(
  <MyComponent />,
  document.getElementById('my-id')
);

这个组件将在多个html中使用,在某些页面中我想渲染一次,在某些页面中,它需要渲染两次:

page1.html

<div id='my-id'></div>

page2.html

<div id='my-id'></div>
<div>some other html</div>
<div id='my-id'></div>

无论如何,为不同的html页面呈现组件一次或两次条件?

2 个答案:

答案 0 :(得分:0)

是的,可以有条件地呈现组件。

render() {}方法中,您可以执行类似......

的操作
render() {
    if (condition1) {
        return (<Component1 id="my-id" />);
    } else 
    if (condition2) {
        return (<Component2 id="my-id" />);
    } else {
        return (<Component3 id="my-id" />);
    }
}

或者如果您需要多个组件,您可以轻松地将它们放在同一个返回块中,假设您使用div(或其他元素)包装它们。

render() {
    return (
        <div>
            <Component1 className="my-className-1" />
            <Component2 className="my-className-2" />
            <Component3 className="my-className-3" />
            <Component1 className="my-className-1" />
            <Component2 className="my-className-2" />
            <Component3 className="my-className-3" />
            <Component1 className="my-className-1" />
            <Component2 className="my-className-2" />
            <Component3 className="my-className-3" />
            ... 
            // You can do as many as you like,
            // components here do not need to be unique.
        </div>
    );
}

最后,还要确保将HTML id属性用作具有多个组件的唯一标识符和HTML class属性。 (JSX使用className btw)

答案 1 :(得分:0)

首先,您必须使用想要的代码构建常量。

所以第1页需要是:

const componentPage1 = (
  <div id='my-id'></div>
)

和第2页类似。

然后您可以使用JSX解决此问题。 JSX将允许您为x === 1:

的条件语句添加Javascript
ReactDOM.render(
    {x === 1
    ? componentPage1
    : componentPage2
  },
  document.getElementById('my-id')
);