简体   繁体   English

在 React JS 中使用 Props 更改 HTML 标签

[英]Changing HTML tag with Props in React JS

I want to display my custom Tire element or simple div (depending on media queries) with different values on each call.我想在每次调用时使用不同的值显示我的自定义轮胎元素或简单的 div(取决于媒体查询)。 But the ternary operator doesn't work (always displays Tire element, never div) and I'm getting "undefined" instead of string "1" that should be it's content.但是三元运算符不起作用(始终显示轮胎元素,从不显示 div)并且我得到的是“未定义”而不是字符串“1”,它应该是它的内容。

Would anyone be so kind as to explain where I went wrong?有人会这么好心解释我哪里出错了吗?

const Content = () => {
  const isDesktop = window.matchMedia('(min-width: 110em)')

  const displayTire = (props) => (isDesktop.matches
    ? <Tire className={`${props.title}`}>{`${props.content}`}</Tire>
    : <div className={`${props.title}`}>{`${props.content}`}</div>)

  displayTire.propTypes = {
    title: PropTypes.string.isRequired,
    content: PropTypes.string.isRequired
  }

  return (
        {displayTire('pneu1', '1')}
  )

export default Content

在此处输入图像描述

The first argument you pass is 'pneu1' .您传递的第一个参数是'pneu1'

This is assigned to the props variable.这被分配给props变量。

You then read props.title .然后你阅读props.title

Strings don't have title properties so the value is undefined.字符串没有title属性,因此该值未定义。


Your prop types says that the first argument should be an object which contains two properties ( title and content ).你的道具类型说第一个参数应该是一个object包含两个属性( titlecontent )。

Pass an object that matches the definition instead of two plain strings.传递与定义匹配的 object 而不是两个纯字符串。

You're not actually providing a title and content to the props of displayTire.您实际上并没有为 displayTire 的道具提供标题和内容。

To do that, you should have done:为此,您应该这样做:

  return (
        {displayTire({ title: 'pneu1', content: '1'})}
  )

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

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