【问题标题】:Conditional rendering in react prop反应道具中的条件渲染
【发布时间】:2021-10-31 02:31:17
【问题描述】:

我想问一下这是否可能在传递道具或类似的东西时做出反应。 Eslint 用红色强调了整个过程。

Component A, 
enter code here
<div>
<button style={{style:props.submit}}> Submit</button>
<button style={{style:props.loading}}> Loading</button>
</div>


Component B
import ComponentA from 'A',

export default class ComponentB extends Component {
constructor(props) {
super();
this.state = {
     load:false,
    }

  handleSubmit = (e) => {
   e.preventDefault();
   this.setState({
    load:true,
  })
 }

 render () {
 return (
 <ComponentA  {this.state.load ? (props.loading): (props.submit)}/>
  )

 }

【问题讨论】:

  • &lt;ComponentA {...this.state.load ? props.loading : props.submit} /&gt;
  • @Martin 我认为这行不通。首先,如果我是正确的,我相信操作顺序会在处理三元之前传播load。其次,我认为它不能自动确定道具名称。
  • 我认为你需要这样做:&lt;ComponentA {...(this.state.load ? {loading: props.loading} : { submit: props.submit})} /&gt;
  • 感谢大家的这些。在尝试实现这些时,需要分配 prop 值,因为它们是样式属性 这会导致错误

标签: reactjs if-statement conditional-statements react-props conditional-rendering


【解决方案1】:

你可以这样使用:

const newProps = this.state.load ? {loading: props.loading} : {submit: props.submit}

<ComponentA  {...newProps} />

【讨论】:

  • 感谢您的回答,道具需要分配值,而且看起来不太可能。我说的是 const newProps = this.state.load 之类的东西? {加载:道具。 loading="none"} : {提交:props.submit="flex"}
  • 什么意思? props . loading="none"
  • props.loading 是一个样式属性。它需要一个值。在组件 A 中,我有类似这样的按钮 style={{style:props.loading}}>Loading
猜你喜欢
  • 2022-01-22
  • 1970-01-01
  • 2019-02-03
  • 2022-12-10
  • 2022-01-17
  • 2019-03-25
  • 2021-05-01
  • 2019-07-26
相关资源
最近更新 更多