对引用使用动态onClick

时间:2019-03-27 08:40:28

标签: javascript reactjs

通过使用<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script> <input class="my-textbox" /> <table id="myTable"> <tr class="header"> <th style="width:60%;">Name</th> <th style="width:40%;">Country</th> </tr> <tr> <td id="name">Alfreds Futterkiste</td> <td>Germany</td> </tr> <tr> <td id="name">Berglunds snabbkop</td> <td>Sweden</td> </tr> </table> <div class="no-results" style="display:none;">No results!</div> <script> var $block = $(".no-results"); $(".my-textbox").keyup(function() { var value = $(this).val().toUpperCase(); var isMatch = false; $("#myTable tr").each(function() { var content = $(this).html(); if (content.toUpperCase().indexOf(value) == -1) { $(this).hide(); } else { isMatch = true; $(this).show(); } }); $block.toggle(!isMatch); }); </script> 传递 onClick =做某事的动态属性可以使我回来:ref listReference在我将在下面显示的组件之一中定义

在组件#1

TypeError: _this.listReference is null

在组件#2

class Component1 extends Component {
    constructor(props){   
        super(props)
        this.listReference= null;
}
//Returns
<div>
 <SomeComponent  list={(ref) => this.listReference= ref} />
 <Component2  onMarkerClick = {(index) => {
                    this.listReference.scrollTop = 48 * index
                                  }}/> 

在组件#3

render() {
const {classes, driversStore, onMarkerCLick} = this.props

...

{driversStore.sortedSelectedOrders.map((order , index) => {
            return (
              <Component3
                onClick={ () => onMarkerClick(index)} />

我希望在单击时触发滚动功能(如组件1中所述)。 预先感谢!

1 个答案:

答案 0 :(得分:1)

  

检查此示例。希望它能对您有所帮助!

const Component2 = (props) =>(
  <button onClick={props.onClick}>click me</button>
);

const SomeCompo = (props) =>(
  <div>SomeComponent</div>
);

class Component1 extends React.Component{
    listReference = React.createRef();
  
    render(){
      return(
        <div>
          <SomeCompo list={this.listReference}>reference</SomeCompo>
          <Component2 onClick={this.handleClick} />
        </div>
      );
    }
    
    handleClick = () => {
    
      if(this.listReference){
       this.listReference={scrollTop:100};
      }
      console.log(this.listReference)
    }
}

ReactDOM.render(<Component1/>,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>

您应该在构造函数中执行以下操作

this.listReference = React.createRef()