反应条件渲染模式 [英] React conditional render pattern

查看:91
本文介绍了反应条件渲染模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经实现了一个Modal组件,它在屏幕上显示了一个模态对话框。通常,模态将有条件地显示。我可以通过两种方式在渲染函数中执行此操作:

  render(){
...
< Modal show = {this.state.showModal}>
//模态中的东西
< / Modal>
}

在Modal组件中,我使用this.props.show添加不同的自我上课。如果为false,则会添加display:none来隐藏模态。



另一种方式是这样的:

  render(){
...
{this.state.showModal&&
(< Modal>
//模态中的东西
< / Modal>)
}
}

这使用 showModal 来决定是否在渲染中添加模态。



我想弄清楚的是:


  1. 这些之间有什么不同两种方式?

  2. 其中一个比另一个好吗?

  3. 还有其他办法吗?

编辑:似乎不同的人有不同的偏好。对我来说,我更喜欢@ErikTheDeveloper所说的。显示/隐藏模态的功能应该保留在模态中,当我们不需要显示模态时,我们可以在模态中返回null。



我想也许对于哪种方式更好没有一定的答案。也许这只是个人选择?

解决方案

我回答了一段与打开/关闭模式的最佳方式



我花了很多钱从那时起React的时间,并在此过程中学到了一些教训。



我发现这种通用方法可以很好地处理模态:使用完全控制的哑巴 需要3个道具的组件。




  • show:Boolean - 模态是否可见?

  • close:函数 - 模态需要a回调以便自行关闭

  • children:node - 模态的内容



参见有关受控组件的信息,请参阅文档






要回答关于两者之间差异的问题,IMO选项1提供了更清晰,更灵活的API,而选项2使用选项1你可以使用CSS 返回 来自< Modal> 。我建议返回 null 因为模态内容将不会被呈现而不是渲染它们并通过CSS隐藏它们。



选项2强制有条理渲染的更详细的JSX方式,我认为在许多情况下是合适的。但是我觉得模态的概念值得隐藏/显示是< Modal> 组件API(道具/方法/等等)的一部分




为什么传递关闭道具/回调?



考虑到大多数模态都有UX,例如关闭事件,例如:按[ESC],单击x,单击模态外部等等...需要通过在下面的示例中传递 close 道具/回调来告知如何关闭自己模式。






代码示例



  //简单,完全受控的Modal组件
const Modal = React.createClass({
render(){
const {
show,// Boolean - 模态是否可见?
close,//函数 - 模态需要一个函数来自我关闭
children,// node - 模态的内容
} = this.props;
return!show?null:(
< ; div className =some-class-for-styling>
< a onClick = {close}> x< / a>
{children}
< / div>
);
}
});

const UsesModal = React.createClass({
setEditing(editing){
this.setState({editing});
},

render(){
//`editing`可以来自任何地方。
//可以从道具派生,
//或在本地作为州管理,任何地方真的....
const {editing} = this.state;
return(
< div>
< h1>一些伟大的组件< / h1>
< a onClick = {()=> this.setEditing(true)}>显示模态!< / a>
<模态show = {editing} close = {()=> this.setEditing(false) }>
一些很棒的模态内容...基于UsesModal.state.editing显示
< / modal>
< / div>
);
}
});






如果你想让模态管理它自己的状态,你可以用一个稍微聪明的组件包装哑模态,并使用refs和公共组件方法(虽然我发现坚持简化的方法通常会减少头痛和后悔;))

  const SmarterModal = React.createClass({
close(){
this.setState({show :false});
},

open(){
this.setState({show:true});
},

render(){
const {children} = this.props;
const {show} = this.state;
return(
< Modal show = {show} close = {this.close}>
{children}
< / modal>
);
}
});

const UsesSmarterModal = React.createClass({
render(){
return(
< div>
< h1> Some Great Component< / h1>
< a onClick = {()=> this.refs.my_smarter_modal.open()}>显示模态!< / a>
< SmarterModal ref =my_smarter_modal >
一些很棒的模态内容......基于SmarterModals自己的内部状态显示
< / SmarterModal>
< / div>
);
}
});

有很多方法可以包含简单的< Modal> ; ,但我觉得它是一个坚实的基础,数据流很好地允许从最有意义的地方计算/推导模态开放。这是我发现的很好的方法。


I have implemented a Modal component that shows a modal dialog on the screen. Normally the modal will show conditionally. There are two ways that I can do this in the render function:

render(){
    ...
    <Modal show={this.state.showModal}>
        // something in modal
    </Modal>
}

In the Modal component, I use this.props.show to add a different class to itself. When this is false, it will add a display:none to hide the modal.

Another way is like this:

render(){
    ...
    { this.state.showModal &&
        (<Modal>
            // something in modal
        </Modal>)
    }
}

This uses showModal to decide whether or not to add the Modal in render.

What I want to figure out is:

  1. What's the different between these two ways?
  2. Is one of them better than the other?
  3. Is there another way to do this?

EDIT: It seems that different persons have different preference. For me myself, I prefer what @ErikTheDeveloper said. The ability that show/hide the Modal should keep inside the Modal, and when we don't need to show the Modal, we can return null in the Modal.

I think maybe there's not a certain answer for which way is better. Maybe it's just personal choice?

解决方案

I answered a similar question a while back relating to the best way of opening/closing modal

I have spent a lot of time with React since then and learned a few lessons along the way.

I've found this general approach to work nicely for dealing with modals: Using a fully controlled "dumb" component that takes 3 props.

  • show: Boolean - Is the modal visible?
  • close: Function - The modal needs a callback in order to close itself
  • children: node - The contents of the modal

See React Docs for info on Controlled Components


To answer your question about the difference between the two, is that IMO option 1 provides a cleaner and more flexible API to work with while option 2 is more minimalist.

With option 1 you could take care of hiding/showing by using either CSS or returning null from <Modal>. I would recommend returning null since the modal contents will simply not be rendered vs. rendering them and "hiding" them via CSS.

Option 2 forces the more verbose "JSX way" of conditionally rendering which I think is appropriate in many cases. However I feel like the concept of a modal merits the hiding/showing being a part of a <Modal> components API (props/methods/etc...)


Why pass down the close prop/callback?

Considering most modals have UX such as closing on events such as: pressing [ESC], clicking "x", clicking outside the modal, etc... a modal needs to be informed of how to "close itself" via passing down the close prop/callback in my examples below.


Code Examples

// The simple, fully controlled Modal component
const Modal = React.createClass({
  render() {
    const {
      show,     // Boolean - Is the modal visible?
      close,    // Function - The modal needs a function to "close itself"
      children, // node - The contents of the modal 
    } = this.props;
    return !show ? null : (
      <div className="some-class-for-styling">
        <a onClick={close}>x</a>
        {children}
      </div>
    );
  }
});

const UsesModal = React.createClass({
  setEditing(editing) {
    this.setState({editing});
  },

  render() {
    // `editing` could come from anywhere. 
    // Could be derived from props, 
    // or managed locally as state, anywhere really....
    const {editing} = this.state;
    return (
      <div>
        <h1>Some Great Component</h1>
        <a onClick={() => this.setEditing(true)}>Show Modal!</a>
        <Modal show={editing} close={() => this.setEditing(false)}>
          Some great modal content... show based on UsesModal.state.editing
        </Modal>
      </div>
    );
  }
});


And if you want to let the modal manage its own state, you can wrap up the "dumb" modal with a slightly smarter component and make use of refs and "public component methods" (although I've found that sticking with the simplified approach usually results in less headache and regret ;))

const SmarterModal = React.createClass({
  close() {
    this.setState({show: false});
  },

  open() {
    this.setState({show: true});
  },

  render() {
    const {children} = this.props;
    const {show} = this.state;
    return (
      <Modal show={show} close={this.close}>
        {children}
      </Modal>
    );
  }
});

const UsesSmarterModal = React.createClass({
  render() {
    return (
      <div>
        <h1>Some Great Component</h1>
        <a onClick={() => this.refs.my_smarter_modal.open()}>Show Modal!</a>
        <SmarterModal ref="my_smarter_modal">
          Some great modal content... show based on SmarterModals own internal state
        </SmarterModal>
      </div>
    );
  }
});

There are a number of ways you can wrap up the simple <Modal>, but I feel like it serves as a solid foundation and the data flow plays nicely to allow computing/deriving "is the modal open" from wherever makes the most sense. This is the approach I've found to work nicely.

这篇关于反应条件渲染模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆