简体   繁体   English

将组件组合到 reactjs 中的变量

[英]Compose components to variable in reactjs

Is it possible to compose more different parts of component to variable?是否可以将组件的更多不同部分组合成变量? documentation文件

const App = () => {
  let element;

  element = <View>
      <Text>text</Text>
    </View>  // --> OK

  element = element + <View>
      <Text>text2</Text>
    </View>  // --> TypeError: Cannot read properties of undefined (reading 'height')

  element.push(<View>
      <Text>text3</Text>
    </View>);  // --> TypeError: element.push is not a function

  return <>
    {element}
  </>
}

export default App;

I use reactjs 17.0.2, typescript and "@react-pdf/renderer": "2.3.0".我使用 reactjs 17.0.2、typescript 和“@react-pdf/renderer”:“2.3.0”。

Update更新

Based on your question here , this should work:根据您的问题,这应该有效:

<Document>
  <Page size="A4" orientation="landscape">
    {/* -- Table LEFT: -- */}
    <View>
      {/* -- Table Head: -- */}
      <View>
        <Text>Index</Text>
        <Text>Brand</Text>
        <Text>Type</Text>
      </View>
      {/* -- Table Body: -- */}
      {data?.cars?.length &&
        data.cars.map(({ id, brand, type }, index) => (
          <View key={`${id}-left`}>
            <Text>{index + 1}</Text>
            <Text>{brand || ''}</Text>
            <Text>{type || ''}</Text>
          </View>
        ))}
    </View>
  </Page>

  <Page size="A4" orientation="landscape">
    {/* -- Table RIGHT: -- */}
    <View>
      {/* -- Table Head: -- */}
      <View>
        <Text>Color</Text>
        <Text>Fuel</Text>
      </View>
      {/* -- Table Body: -- */}
      {data?.cars?.length &&
        data.cars.map(({ id, color, fuel }) => (
          <View key={`${id}-right`}>
            <Text>{color || ''}</Text>
            <Text>{fuel || ''}</Text>
          </View>
        ))}
    </View>
  </Page>
</Document>

The issue seems to be with how you're handling arrays , not with rending React elements.问题似乎在于您如何处理 arrays ,而不是渲染 React 元素。

If you want to access the properties of the object in an array element, you can destructure the element, so instead of如果要访问数组元素中 object 的属性,可以解构该元素,因此

data.cars.map((car, index) => (<Text>{car.color}</Text>))

you can do你可以做

data.cars.map(({id, brand, type, color, fuel}, index) => (<Text>{color}</Text>));

If you're not performing any operations on the array elements, you can use an implicit return instead of an explicit return:如果您不对数组元素执行任何操作,则可以使用隐式返回而不是显式返回:

// explicit return
data.cars.map(({id, brand, type, color, fuel}, index) => { 
  // do something else here
  return (
    <Text>{color}</Text>
  )
});
// implicit return
data.cars.map(({id, brand, type, color, fuel}, index) => (<Text>{color}</Text>));

Also, when you're rending known text values in React, you don't need to wrap it in curly braces ( {} ), you can just render the text directly.此外,当您在 React 中渲染已知文本值时,您不需要将其包裹在花括号 ( {} ) 中,您可以直接渲染文本。

Instead of代替

<Text>{'color'}</Text>

you can just put你可以把

<Text>color</Text>

unless it's required by whatever library you're using.除非您使用的任何库都需要它。 I'm not familiar with @react-pdf/renderer .我不熟悉@react-pdf/renderer

One more thing to keep in mind is that the key for list items in React should be something stable.还有一件事要记住,React 中列表项的key应该是稳定的。 Using array indices as keys is discouraged ( see React docs ).不鼓励使用数组索引作为键(参见 React 文档)。


Original answer原始答案

If you want to render an element this way, you could do something like this:如果你想以这种方式渲染一个元素,你可以这样做:

const App = () => {
  let element = [];

  // Each child in a list needs a unique "key" prop
  element.push(<View key={someUniqueKey}>
      <Text>text</Text>
    </View>)

  element.push(<View key={someOtherUniqueKey}>
      <Text>text2</Text>
    </View>)

  element.push(<View key={oneMoreUniqueKey}>
      <Text>text3</Text>
    </View>);

  return <>
    {element}
  </>
}

export default App;

Personally, I haven't seen anyone render components like this.就个人而言,我还没有看到有人像这样渲染组件。

The strategy you are looking for is called conditional rendering , and there are different ways to do this depending on the situation.您正在寻找的策略称为条件渲染,根据情况有不同的方法可以做到这一点。

For example, if you're trying to dynamically render data from an API response, you could do something like this:例如,如果您尝试从 API 响应中动态呈现数据,您可以执行以下操作:

const App = () => {
  const { data } = fetchDataFromAPI();

  return (
    <>
      <View>
        <Text>text</Text>
      </View>

      {data?.text2 && (
        <View>
          <Text>{data.text2}</Text>
        </View>
      )}

      {data?.text3 && (
        <View>
          <Text>{data.text3}</Text>
        </View>
      )}
    </>
  );
};

export default App;

You can check out the React docs for conditional rendering and rendering lists .您可以查看 React 文档以了解条件渲染渲染列表

(Note: The above links are for the beta docs. If you prefer the classic(?) docs: conditional rendering and lists ) (注意:以上链接适用于 beta 文档。如果您更喜欢经典(?)文档:条件渲染列表

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM