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

时间:2020-01-30 00:21:55

标签: javascript reactjs

我有一个子组件,我遍历数组以打印出标题和值。我有一个事件监听器,它呈现标题和值的新行。我在子组件中有一个按钮,我不想默认显示它,而仅在添加新行时才显示。因此,每2行将有一个按钮,每3行将有2个,依此类推。

这是我的app.js文件

library(stringr)
library(data.table)
Fun <- function(x){
  n_slash <- str_count(x, "/")
  pattern <- paste0(rep(".*/", n_slash-1), collapse="")
  pattern1 <- paste0(pattern, "(.*)/.*", collapse="")
  pattern2 <- paste0(pattern, ".*/(.*)", collapse="")
  secondlast <- gsub(pattern1, "\\1", x)
  last <- gsub(pattern2, "\\1", x)
  return(data.frame(url=x,secondlast=secondlast, last=last))
}
# execute the function and bind the results in a dataframe
extracted <- rbindlist(lapply(urls, Fun))
extracted
    1:       https://domain.ca/courses/43/pages/general-guidelines      pages   general-guidelines
    2:      https://domain.ca/courses/43/id=33/svgl11/hi/resources         hi            resources
    3: https://domain.ca/courses/43/505/pages/detail-specification      pages detail-specification

这是我的子组件的设置:-

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;

因此,基本上,默认情况下不应显示名为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 的子组件中的按钮,而应在此后每次单击后显示。谢谢。

1 个答案:

答案 0 :(得分:1)

使用map循环的索引向父对象添加一个prop。然后添加一个标记,这样只有第一个渲染后的子代才能获得“新块!”按钮:

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