JSX在运行时选择类型

2018-08-06  本文已影响18人  JamesSawyer

不能使用一个普通的表达式作为React元素类型。如果想要使用普通表达式来表示元素类型,首先需要将其赋值给大写的变量

这通常会出现在根据不同的props渲染不同组件时:

import React from 'react';
import { PhotoStory, VideoStory } from './stories';

const components = {
  photo: PhotoStory,
  video: VideoStory
};

function Story(props) {
  // 错误, JSX类型不能是表达式
  return <components[props.storyType] story={props.story} />
}

为了解决这个问题,首先需要将表达式赋值给一个以大写字母开头的变量:

import React from 'react';
import { PhotoStory, VideoStory } from './stories';

const components = {
  photo: PhotoStory,
  video: VideoStory
};

function Story(props) {
  // 正确!JSX 类型可以是一个以大写字母开头的变量.
  const SpecificStory = components[props.storyType];
  return <SpecificStory story={props.story} />;
}

来源:

上一篇 下一篇

猜你喜欢

热点阅读