2017-09-28 81 views
0

我試圖使用React和Typescript創建一個簡單的標籤應用程序。我有一個名爲Tabs的Container組件處理狀態並將其傳遞給我的內容組件。我也創建了一個。稱爲'handleName'的函數,我將它傳遞給我稱爲側欄的功能組件。當函數被觸發時,它應該更新我的狀態,從而重新呈現我的內容組件。但是,它不起作用。而且我的控制檯也沒有出現任何錯誤。它只是沒有做任何事情。從容器傳遞函數到React + TypeScript中的功能組件

這裏是我的標籤(容器)

import * as React from 'react'; 
import Sidebar from './Sidebar'; 
import Content from './Content'; 
import './css/Tabs.css'; 

export interface State { 
    message: string; 
} 

class Tabs extends React.Component<{}, State> { 
    public state: State = { 
     message: 'Select a name from the tabs menu', 
    }; 

    componentWillMount() { 
     if ('pluginLoaded' in window) { 
      (window as any).pluginLoaded('hello', function (port: any, context: any) { 
       // Future work should interact with the message channel here 
      }); 
     } 
    } 

    handleName(value: string) { 
     if (value === 'Vanessa') { 
      this.setState({ 
       message: 'Vanessa means "butterfly"' 
      }); 
     } else if (value === 'Paola') { 
      this.setState({ 
       message: 'Paola means "small"' 
      }); 
     } 
    } 

    render() { 
     return (
      <div className="Tabs"> 
       <p>Tabs</p> 
       <Sidebar handleName={() => this.handleName}/> 
       <Content message={this.state.message}/> 
      </div> 
     ); 
    } 
} 

export default Tabs; 

這裏是我的邊欄

import * as React from 'react'; 

export interface Props { 
    handleName: (value: String) => void; 
} 

const Sidebar: React.StatelessComponent<Props> = (props) => { 

    // declare constants 
    const Vanessa = 'Vanessa', 
     Paola = 'Paola'; 

    return(
     <div className="Sidebar"> 
      <h1>Tabs</h1> 
      <ul> 
       <li><a onClick={() => props.handleName(Vanessa)}>Vanessa</a></li> 
       <li><a onClick={() => props.handleName(Paola)}>Paola</a></li> 
      </ul> 
     </div> 
    ); 
}; 

export default Sidebar; 

這裏是我的內容

import * as React from 'react'; 

export interface Props { 
    message: string; 
} 

const Content: React.StatelessComponent<Props> = (props) => { 

    return(
     <div className="Content"> 
      <h1>Find the meaning</h1> 
      <p>{props.message}</p> 
     </div> 
    ); 
}; 

export default Content; 

回答

1

變化

<Sidebar handleName={() => this.handleName}/> 

<Sidebar handleName={this.handleName}/> 

還可以使用箭頭功能綁定handleName類範圍

handleName = (value: string) => { 
+0

@vanegeek看答案。爲handleName使用箭頭函數。所以將你的方法定義從'handleName(value:string){'轉換爲''handleName =(value:string)=> {' –

+0

非常感謝你Prakash !!!!!!!! – vanegeek