简体   繁体   English

有条件地渲染 React JS 中的元素?

[英]Conditionally render elements in React JS?

I have a child component which i am looping over array to print out title and values.我有一个子组件,我正在遍历数组以打印出标题和值。 I have an event listener which renders a new row of title and values.我有一个事件侦听器,它呈现新的标题和值行。 I have a button in child component which i want do not want to be displayed by default but rendered only when i add new rows.我在子组件中有一个按钮,我不想在默认情况下显示该按钮,但仅在添加新行时才呈现该按钮。 So every 2 rows, there will be one button, for every 3, there will be 2 and so on.所以每 2 行,就会有一个按钮,每 3 行,就会有 2 个,以此类推。

This is my app.js file这是我的 app.js 文件

import React, {Component} from 'react';
import './App.css';
import Child from './Child.js'

class App extends Component {
   state = {
      myArray: [
       { title: 'Hello', value: 'hello' }
     ]
   }

 addNewField = () => {
    const myArray = [...this.state.myArray, { title: 'Hello', value: 'hello' }]
     this.setState ({
    myArray
  })
}

render() {
  return (
    <div className = "App">
   {
    this.state.myArray.map ( (val,idx) => {
      return (
        <Child
        key = {idx}
        title = {val.title}
        animal = { val.value }
        />
      )
    })
  }
  <button onClick = {this.addNewField}>Add Me</button>
</div>
   )
 }
}
export default App;

This is the setup for my Child Component:-这是我的子组件的设置:-

import React from 'react'

const Child = (props) => {
  return (
     <div>
        <h3>{props.title}</h3>
        <h4>{props.value}</h4>
        <button>New Block!!</button>
    </div>
   )
}

 export default Child

So basically the button in the Child component named new block should not be displayed by default but only after every click there after.所以基本上名为new block的 Child 组件中的按钮不应该默认显示,而只能在每次点击之后显示。 Thank you.谢谢你。

Add a prop to the parent with the index of the map loop.使用地图循环的索引向父级添加一个道具。 Then add a flag so only children rendered after the first get the "New Block!!"然后添加一个标志,以便只有在第一个之后渲染的孩子才能获得“新块!!” button:按钮:

render() {
  return (
    <div className = "App">
   {
    this.state.myArray.map ( (val,idx) => {
      return (
        <Child
        key = {idx}
        title = {val.title}
        animal = { val.value }
        renderIndex = {idx}
        />
      )
    })
  }
  <button onClick = {this.addNewField}>Add Me</button>
</div>
   )
 }
}
import React from 'react'

const Child = (props) => {
  return (
     <div>
        <h3>{props.title}</h3>
        <h4>{props.value}</h4>
        {props.renderIndex > 0 && <button>New Block!!</button>}
    </div>
   )
}
export default Child

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

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