【问题标题】:Using jQuery inside of a React render function在 React 渲染函数中使用 jQuery
【发布时间】:2016-03-03 18:40:19
【问题描述】:

我有以下 React 渲染函数:

   render: function () {
        return (
            <Popup onClose={this.props.onClose}>
                <Form entity="strategy" edit="/strategies/edit/" add="/strategies/add/">
                    <h2>Create/Edit Strategy</h2>
                    <StrategyForm pending={this.state.pending} formData={this.state.data} />
                    <div className="col-md-6">
                        <Assisting />
                    </div>
                </Form>
            </Popup>
        );
    }

我想让 h2 标题基于 body 类,所以我的问题是……我可以这样做吗?

    render: function () {
        return (
            <Popup onClose={this.props.onClose}>
                <Form entity="strategy" edit="/strategies/edit/" add="/strategies/add/">
                    if ( $('body').hasClass("this") ) {
                     <h2>Create This Strategy</h2>
                    } else {
                     <h2>Create Another Strategy</h2>
                    }
                    <StrategyForm pending={this.state.pending} formData={this.state.data} />
                    <div className="col-md-6">
                        <Assisting />
                    </div>
                </Form>
            </Popup>
        );
    }

如果这是一个糟糕的想法,有人能告诉我在 React 中有什么更好的方法吗?

【问题讨论】:

  • 这可能是个坏主意(绝对没有理由为此使用 jQuery),但您实际上想做什么?
  • @tobiasandersen 我是这么认为的。我只是想根据正文类返回两个不同的标头。
  • 虽然可以按照您的要求去做,但这不是做它的“反应方式”。你是否只为这个组件使用 React?您何时、如何以及为什么设置 body 类?
  • @tobiasandersen Web 应用程序有两个部分。站点的外观基于 body 类。所以只有两个身体类别的可能性。我对许多组件和大部分前端使用 react。但我在这件作品上遇到了麻烦。如上所示,我无法使用 jQuery,所以来这里寻求帮助

标签: javascript jquery if-statement reactjs jsx


【解决方案1】:

正如在 OP 上的一些 cmets 中已经指出的那样,您可以这样做,但这并不是真正的“React”方式。

更好的解决方案可能是将prop 传递到组件的使用中,或者在组件的状态上设置一个标志——然后使用该道具/标志进行渲染。

伪代码:

render() {
    return (
        if (this.props.someProp) {
            <h2>Create this Strategy</h2>
        } else {
            <h2>Create this Strategy</h2>
        }
    );
}

IMO 在组件方法中使用 jQuery 很好(例如 componentDidMount(),或其他事件/实用程序方法),但通常你会希望在 render() 中避免这种情况。 React 组件的全部目的是维护状态,因此像您的示例一样即时使用 jQuery 会破坏这个想法。


例如,假设您以这种方式渲染组件:

ReactDOM.render(<MyComponent />, document.getElementById('some-div'));

您可以将属性传递给您的组件:

ReactDOM.render(
    <MyComponent someProp={true} />, 
    document.getElementById('some-div')
);

或者在你的情况下:

ReactDOM.render(
    <MyComponent someProp={$('body').hasClass("this")} />, 
    document.getElementById('some-div')
);

...类似的东西。这是一个过于简化的示例(未经测试,因此请注意语法错误),但这应该有助于解释我的思考过程。


或者,您可以在您的类上使用componentDidMount() 方法。

componentDidMount() {
    this.setState({ 
        someProp : $('body').hasClass("this")
    });
}

然后在render() 中检查this.state.someProp

【讨论】:

  • 感谢您的回答。我没有编写 React 函数,但现在正在里面工作。你能给我一些关于如何根据身体类别创建道具的见解吗?抱歉,我不清楚这是如何工作的。
  • 已更新示例:-)
猜你喜欢
  • 2023-01-04
  • 1970-01-01
  • 2020-06-23
  • 2016-03-14
  • 1970-01-01
  • 2018-12-24
  • 2021-12-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多