【问题标题】:how to show persons dynamically in React function based components如何在基于 React 函数的组件中动态显示人员
【发布时间】:2020-10-24 14:15:42
【问题描述】:

我使用的是函数组件而不是基于类的组件。所以我想在单击按钮时动态显示人员数据

const App = props =>{
   const [showPersons, setShowPersons] = useState({
        showPersons : false,
   })
   const togglePersonsHandler = () => {
        let temp = showPersons.showPersons;
        setShowPersons({showPersons : !temp});
   }

没有render() 方法。所以基于函数的组件未呈现if 条件。

    let persons = null;
    if(showPersons.showPersons){
      persons = (
       <div>
          <Person name={personsState.persons[0].name} location={personsState.persons[0].location} />
          <Person name={personsState.persons[1].name} location={personsState.persons[1].location} 
            click={() => swichNameHandler('Nagi')} changed={nameChangeHandler}>his job is internet business
          </Person>
          <Person name={personsState.persons[2].name} location={personsState.persons[2].location}/>   
      </div>
    )
  }
  return(
    <div className="App">
        <h1>Hello there, this is nagasai </h1>
        <button style={inlineStyles} 
        onClick={togglePersonsHandler}>Toggle Persons
        </button>
        {person}
    </div>
  )
}
export default App;

任何人都可以帮我解决这个问题。

【问题讨论】:

  • 你的useState 默认应该是false 而不是使用一个对象。还有一个错字:personpersons
  • @jmargolisvt 知道了,谢谢...)

标签: javascript reactjs react-component


【解决方案1】:

只使用条件

<div>
  {showPersons.showPersons &&
    <div>
      <Person ... />
      <Person ... />
    </div>
  }
</div>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-12-21
    • 2020-06-29
    • 2017-02-03
    • 2022-11-11
    • 2020-04-05
    • 1970-01-01
    • 2019-11-26
    • 2021-05-12
    相关资源
    最近更新 更多