【问题标题】:Having an item appear conditionally in another component让一个项目有条件地出现在另一个组件中
【发布时间】:2021-11-02 20:50:28
【问题描述】:

我有一个导航组件:

class SomeClass extends React.Component{
    
    showItem = () =>{
        console.log("itemShown");
        return(
            <Item/>
        );
    }
    
    render(){
    
        return(
            <div onClick={() => this.showItem()} >
                ABC
            </div>
        );
}

export default Nav;

我在 App.js 中调用它:

function App() {
  return (
      <div className="app">
          <SomeClass />
      </div>
    );
    
}

export default App;

如何在SomeClassshowItem方法中拥有Item组件,在App中显示功能组件。

App.js 我试过了:

<div className="app">
    <SomeClass showItem={showItem} />
</div>

但是,它不起作用。

最好的方法是什么?

【问题讨论】:

    标签: javascript reactjs react-router react-hooks


    【解决方案1】:

    现在人们不倾向于使用 React 类,而是使用函数式组件。以下是使用功能组件的方法。

    状态挂钩:

    toggleShowItemtruefalse 之间交换showItem 状态,当SomeClass(它不再是一个类,但这是你命名的)组件的onClick 被触发时。

    条件渲染:

    只要状态挂钩的值为true,就会呈现ShowItem

    export default function App() {
        const [showItem, setShowItem] = useState(false);
    
        const toggleShowItem = () => {
            setShowItem(!showItem);
        }
    
        return (
            <div className="App">
                <SomeClass toggleShowItem={toggleShowItem}>
                    {showItem && <ShowItem />}
                </SomeClass>
            </div>
        );
    }
    
    export default function SomeClass({toggleShowItem}) {
        return <div onClick={toggleShowItem}>ABC</div>;
    }
    

    【讨论】:

      【解决方案2】:

      您可以按如下方式管理SomeClass 组件内的状态。然后,您可以在需要显示或取消显示 Item 组件时切换它。

      class SomeClass extends React.Component {
        constructor(props) {
          super(props);
          this.state = {
            isShowItem: false,
          };
          this.showItem = this.showItem.bind(this);
        }
      
        showItem = () => {
          this.setState(!this.state.isShowItem);
        };
      
        render() {
          return (
            <>
              <div onClick={this.showItem}>ABC</div>
              {this.state.isShowItem && <Item />}
            </>
          );
        }
      }
      export default SomeClass;
      

      【讨论】:

        【解决方案3】:

        显示Item 组件的更好方法是使用React StateReact Props。请阅读此文档,因为它将极大地帮助您进行 React 开发。

        选项 1:

        App 组件中将有一个用于showItem 的状态。然后你将showItem 作为SomeClass 组件中的道具传递。

        选项 2:

        showItem 的状态在 SomeClass 组件中,然后单击切换,状态将被更新。

        【讨论】:

          【解决方案4】:

          您可以使用两种方式。 仅当状态发生一些变化时才反应更新。你没有操纵任何状态 另一种方法是从 display: none 到 display: block

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2016-06-24
            • 1970-01-01
            • 1970-01-01
            • 2021-02-23
            • 1970-01-01
            相关资源
            最近更新 更多