函数在render()外部的React中不起作用

问题描述 投票:0回答:1

我的函数在react render函数之外无法正常工作。当我使用函数代码而不在渲染器内部使用函数时,它将起作用。我在哪里做错了。

反应:

class App extends React.Component {
  constructor(props) {
   super(props);
   this.state={
    calcKeys:[
     {
       "key": "AC",
      },
      {
        "key": "CE",
      },
      {
        "key": "±",
       },
       {
        "key": "/",
        },
        {
         "key": "7",
        },
       ]
      };
      this.displayKeys = this.displayKeys.bind(this);
   }
   displayKeys() {
     <div className="display-keys"> 
       <div className="screen">
          <input type="text" />
        </div>
             {this.state.calcKeys.map(item=>
                <button>{item.key}</button>
             )}
      </div>
   }
   render() {
     return(
       <div className="display-container">
         <displayKeys />
       </div> 
     );
    }
} 
ReactDOM.render(<App />, document.getElementById("root"));
reactjs
1个回答
1
投票

将return关键字添加到displayKeys

displayKeys() {
     return <div className="display-keys"> 
     //...
    </div>
}

并且使用此正弦波调用内部渲染函数:{this.displayKeys()}而不是<displayKeys/>

不要使用<displayKeys/>,因为React会将其视为独立的组件。如果这样做,则在其他组件上提取displayKeys。例如:

const Keys = ({calcKeys})=>(<div className="display-keys"> 
  <div className="screen">
     <input type="text" />
  </div>
  {calcKeys.map(item=><button>{item.key}</button>)}
</div>)

class App extends Component{
//...
  render(){
     return(
       <div className="display-container">
         <Keys calcKeys={this.state.calcKeys}/>
       </div> 
     );
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.