【问题标题】:How to create a function which calls a tag in reactjs? [closed]如何在reactjs中创建一个调用标签的函数? [关闭]
【发布时间】:2019-12-02 10:20:03
【问题描述】:

我想在 reactjs 中创建一个函数,它会有这样的标签:

export class Counter extends Component {
    anyFunction() {
        return <h1>Hello there</h1>;
    }
    render() {
        return (
          <React.Fragment>
            {this.anyFunction()}
          </React.Fragment>
           );
    }
}

有可能吗?我想在函数中调用标签,然后想作为返回语句调用。

【问题讨论】:

  • 就写吧。您的代码似乎正确。

标签: javascript reactjs jsx


【解决方案1】:

您不能在需要创建第二个组件的内部类或功能组件中创建

const AnyFunction = (props) => (
  <h1>Hello there</h1>
)

export class Counter extends Component {
    render() {
        return (
          <React.Fragment>
            <AnyFunction />
          </React.Fragment>
           );
    }
}

用于条件渲染

const AnyFunction = (props) => (
  <h1>Hello there</h1>
)

export class Counter extends Component {
    render() {
        return (
          <React.Fragment>
            { num === 1 && <AnyFunction /> }
            { num === 1 ? <AnyFunction /> : <AnyOtherFunction /> }
          </React.Fragment>
           );
    }
}

【讨论】:

  • 如果我想添加一个 if 语句 if num === 1 怎么办?
  • @SankalpBhatia 我已经更新了我的帖子,如果它的帮助已满,请点赞
  • @SankalpBhatia 你也可以这样做{ num === 1 ? &lt;AnyFunction /&gt; : &lt;AnyOtherFunction /&gt; }
  • 条件渲染不适用于自定义标签。我用另一个 .js 文件创建了一个 标记,但它没有按预期返回
  • @SankalpBhatia 请提供更多详细信息,您是如何创建 another.js 的
【解决方案2】:

你可以这样做

export class Counter extends Component {

    render() {
    var someTag = <h1>Hello there</h1>;
        return (
          <React.Fragment>
            {someTag}
          </React.Fragment>
           );
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-06-15
    • 1970-01-01
    • 1970-01-01
    • 2012-02-20
    • 2021-08-08
    • 1970-01-01
    • 2018-09-22
    • 2013-09-05
    相关资源
    最近更新 更多