我第一次摆弄React.js,找不到一种方法通过单击事件在页面上显示或隐藏一些东西。我没有加载任何其他库到页面,所以我正在寻找一些使用React库的本地方式。这是我目前得到的。我想在点击事件触发时显示结果div。

var Search= React.createClass({
    handleClick: function (event) {
        console.log(this.prop);
    },
    render: function () {
        return (
            <div className="date-range">
                <input type="submit" value="Search" onClick={this.handleClick} />
            </div>
        );
    }
});

var Results = React.createClass({
    render: function () {
        return (
            <div id="results" className="search-results">
                Some Results
            </div>
        );
    }
});

React.renderComponent(<Search /> , document.body);

当前回答

如果你想看看如何TOGGLE显示一个组件签出这小提琴。

http://jsfiddle.net/mnoster/kb3gN/16387/

var Search = React.createClass({
    getInitialState: function() {
        return { 
            shouldHide:false
        };
    },
    onClick: function() {
        console.log("onclick");
        if(!this.state.shouldHide){
            this.setState({
                shouldHide: true 
            })
        }else{
                    this.setState({
                shouldHide: false 
            })
        }
    },
render: function() {
    return (
      <div>
        <button onClick={this.onClick}>click me</button>
        <p className={this.state.shouldHide ? 'hidden' : ''} >yoyoyoyoyo</p>
      </div>
    );
}
});

ReactDOM.render( <Search /> , document.getElementById('container'));

其他回答

下面是三元操作符的另一种语法:

{ this.state.showMyComponent ? <MyComponent /> : null }

等价于:

{ this.state.showMyComponent && <MyComponent /> }

学习的原因


还有显示的替代语法:'none';

<MyComponent style={this.state.showMyComponent ? {} : { display: 'none' }} />

然而,如果你过度使用display: 'none',这将导致DOM污染,并最终降低应用程序的速度。

只要找到一种新的、神奇的方法来使用(useReducer)功能组件

const [state, handleChangeState] = useReducer((state) => !state, false); 改变状态

在某些情况下,高阶分量可能有用:

创建高阶组件:

export var HidableComponent = (ComposedComponent) => class extends React.Component {
    render() {
        if ((this.props.shouldHide!=null && this.props.shouldHide()) || this.props.hidden)
            return null;
        return <ComposedComponent {...this.props}  />;
    }
};

扩展你自己的组件:

export const MyComp= HidableComponent(MyCompBasic);

然后你可以这样使用它:

<MyComp hidden={true} ... />
<MyComp shouldHide={this.props.useSomeFunctionHere} ... />

这减少了一点样板文件,并强制坚持命名约定,但请注意,MyComp仍然会被实例化-省略的方法是前面提到的:

{ !hidden &&; <MyComp ... /> }

// Try this way

class App extends Component{

  state = {
     isActive:false
  }

  showHandler = ()=>{
      this.setState({
          isActive: true
      })
  }

  hideHandler = () =>{
      this.setState({
          isActive: false
      })
  }

   render(){
       return(
           <div>
           {this.state.isActive ? <h1>Hello React jS</h1> : null }
             <button onClick={this.showHandler}>Show</button>
             <button onClick={this.hideHandler}>Hide</button>
           </div>
       )
   }
}

状态和效果的应用程序已经并且必须封装在同一个组件中,因此,没有什么比创建一个自定义组件作为钩子来解决在这种情况下是使特定的块或元素可见还是不可见更好的了。

// hooks/useOnScreen.js

import { useState, useEffect } from "react"

const useOnScreen = (ref, rootMargin = "0px") => {

  const [isVisible, setIsVisible] = useState(false)

  useEffect(() => {
    const observer = new IntersectionObserver(
      ([entry]) => {
        setIsVisible(entry.isIntersecting)
      },
      {
        rootMargin
      }
    );

    const currentElement = ref?.current

    if (currentElement) {
      observer.observe(currentElement)
    }

    return () => {
      observer.unobserve(currentElement)
    }
  }, [])

  return isVisible
}

export default useOnScreen

然后自定义钩子嵌入到组件中

import React, { useRef } from "react";
import useOnScreen from "hooks/useOnScreen";

const MyPage = () => {

  const ref = useRef(null)

  const isVisible = useOnScreen(ref)

  const onClick = () => {
    console.log("isVisible", isVisible)
  }
  
  return (
    <div ref={ref}>
      <p isVisible={isVisible}>
        Something is visible
      </p>
      <a
        href="#"
        onClick={(e) => {
          e.preventDefault();
          onClick(onClick)
        }}
      >
        Review
      </a>
    </div>
  )
}

export default MyPage

由useRef钩子控制的ref变量,允许我们在DOM中捕获我们想要控制的块的位置,然后由useOnScreen钩子控制的isVisible变量,允许我们通过useRef钩子在块内部设置I信号。 我相信useState、useeffect和useRef钩子的实现允许您通过使用自定义钩子将它们分开来避免组件呈现。

希望这些知识对你有用。