我第一次摆弄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);

当前回答

var Search = React.createClass({ getInitialState: function() { return { showResults: false }; }, onClick: function() { this.setState({ showResults: true }); }, render: function() { return ( <div> <input type="checkbox" value="Search" onClick={this.onClick} /> { this.state.showResults ? <Results /> : null } </div> ); } }); var Results = React.createClass({ render: function() { return ( <div id="results" className="search-results"> <input type="text" /> </div> ); } }); ReactDOM.render( <Search /> , document.getElementById('container')); <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.6.2/react.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/15.6.2/react-dom.min.js"></script> <div id="container"> <!-- This element's contents will be replaced with your component. --> </div>

其他回答

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

创建高阶组件:

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 ... /> }

这个例子展示了如何通过使用每1秒切换一次的toggle来在组件之间切换

import React ,{Fragment,Component} from "react";
import ReactDOM from "react-dom";

import "./styles.css";

const Component1 = () =>(
  <div>
    <img 
src="https://i.pinimg.com/originals/58/df/1d/58df1d8bf372ade04781b8d4b2549ee6.jpg" />
   </div>
)

const Component2 = () => {
  return (
    <div>
       <img 
src="http://www.chinabuddhismencyclopedia.com/en/images/thumb/2/2e/12ccse.jpg/250px- 
12ccse.jpg" />
  </div>
   )

 }

 class App extends Component {
   constructor(props) {
     super(props);
    this.state = { 
      toggleFlag:false
     }
   }
   timer=()=> {
    this.setState({toggleFlag:!this.state.toggleFlag})
  }
  componentDidMount() {
    setInterval(this.timer, 1000);
   }
  render(){
     let { toggleFlag} = this.state
    return (
      <Fragment>
        {toggleFlag ? <Component1 /> : <Component2 />}
       </Fragment>
    )
  }
}


const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

根据文档,最佳实践如下:

{this.state.showFooter && <Footer />}

只有在状态有效时才呈现元素。

使用rc-if-else模块

npm install --save rc-if-else
import React from 'react';
import { If } from 'rc-if-else';

class App extends React.Component {
    render() {
        return (
            <If condition={this.props.showResult}>
                Some Results
            </If>
        );
    }
}

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

// 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钩子的实现允许您通过使用自定义钩子将它们分开来避免组件呈现。

希望这些知识对你有用。