如何在React类函数中返回元素

时间:2019-04-18 19:35:10

标签: reactjs

如何通过单击返回React类函数中的元素。甚至有可能吗?

class Item extends Component {
  constructor(props) {
    super(props);
    this.itemInfo = this.itemInfo.bind(this);
  }


  itemInfo = () =>{ 
   return <div> some info</div>

  }


  render(){
   return(
     <div>
       <div onClick={this.itemInfo}> Click Here <div>
     </div>
    )
   }

 }

4 个答案:

答案 0 :(得分:1)

class Item extends React.Component {
  state = {
    showDiv: false
  };

  render() {
    return (
      <div>
        <div
          style={{ cursor: "pointer" }}
          onClick={() =>
            this.setState(prevState => ({
              showDiv: !prevState.showDiv
            }))
          }
        >
          Click Me
        </div>
        {/*Show the INFO DIV ONLY IF THE REQUIRED STATE IS TRUE*/}
        {this.state.showDiv && <InfoDiv />}
      </div>
    );
  }
}

//This is the div which we want on click
var InfoDiv = () => (
  <div style={{ border: "2px solid blue",borderRadius:10, padding: 20 }}>
    <p> Long Text DIVLong Text DIVLong Text DIVLong Text DIVLong Text DIV </p>
  </div>
);
ReactDOM.render(<Item />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

<div id="root"></div>

答案 1 :(得分:0)

您应该在state中执行此操作。

  itemInfo = () =>{ 
   this.setState({ component:<div> some info</div> }); 
  }

并像这样渲染组件

 return(
     <div>
       <div onClick={this.itemInfo}> Click Here <div>
        {this.state.component}
     </div>
    )

答案 2 :(得分:0)

您可以使用状态和条件渲染来尝试类似的事情:

class Item extends Component {
  constructor(props) {
    super(props)

    this.state = {
      showMore: false,
    }
  }

  toggleShowMore = () => {
    this.setState({ showMore: !this.state.showMore })
  }

  render() {
    return (
      <div>
        <div onClick={this.toggleShowMore}>
          {this.state.showMore ? 'Show less' : 'Show more'}
        </div>

        {this.state.showMore ? <div>some info</div> : null}
      </div>
    )
  }
}

答案 3 :(得分:0)

这是我要怎么做:


function ItemInfo() {
  return(
    <div>Some Info</div>
  );
}


class Item extends Component {
  constructor(props) {
    super(props);
    this.handleClick= this.handleClick.bind(this);
    this.state = {
      showInfo: false
    }
  }

 handleClick() {
   this.setState((prevState) => {showInfo: !prevState.showInfo});
 }


  render(){
   return(
     <div>
       <div onClick={this.handleClick}> Click Here <div>
       { this.state.showInfo ? 
          <ItemInfo/>
          : null }
     </div>
    )
   }

 }