2016-04-03 3 views
1

まず最初に、私はReactで新しいです。私は2つのコンポーネント、TagUtilsUrlsを持っています。ルータのパラメータをUrlsからTagUtilsに渡そうとしています。ここに私のコードです:コンポーネント間でデータを受け渡ししようとすると未定義になる

Urls.jsx

私はそれはちょうど私が何かをしないのです undefined .Maybeを示す[削除]ボタンをクリックした
// some codes.... 
export default class Urls extends React.Component { 

render() { 
return (
    <div> 
     <TagUtils tag={this.props.params.tag_id}/> 
    </div> 
) 
} 
} 

TagUtils.jsx

export default class TagUtils extends React.Component { 

    deleteTag(props) { 
     console.log(props.tag); 
    } 

    render() { 
     return (
      <div className="col-xs-6 col-md-4"> 
       <button type="button" className="btn btn-danger" onClick={this.deleteTag}><i className="fa fa-trash"> Delete</i></button> 
      </div> 
     ) 
    } 
} 

。あなたの例では

+0

あなたがコンソールにthis.props.params.tag_id見ることができますか? this.props.tag_idを使用していて、tag_Idをどこかに設定する必要があります。そのコードを確認できますか? – JordanHendrix

+0

React es6 classe docs:https://facebook.github.io/react/docs/reusable-components.html#es6-classes – JordanHendrix

答えて

1
this.propsを通じてコン​​ポーネント propsを得ることができます必要があります

ReactをcreateClassからES6 classesに変更すると、http://www.newmediacampaigns.com/blog/refactoring-react-components-to-es6-classesのように私たち自身のメソッドに対して正しい値thisを処理する必要がありますメソッドはコンストラクタでこのの正しい値に囲ま持っているあなたのコードを変更し:

export default class TagUtils extends React.Component { 
    constructor(props) { 
     super(props); 
     this.deleteTag = this.deleteTag.bind(this); 
    } 

    deleteTag(props) { 
    console.log(props.tag); 
    } 

    render() { 
    return (
     <div className="col-xs-6 col-md-4"> 
      <button type="button" className="btn btn-danger" onClick={this.deleteTag}><i className="fa fa-trash"> Delete</i></button> 
     </div> 
    ) 
    } 
} 

no autobindingはES6クラスのみんなに反応からの意図的なステップでした。コンテキストを修正する自動バインディングはReact.createClassで提供されました。これの詳細はここで見つけることができます:https://facebook.github.io/react/blog/2015/01/27/react-v0.13.0-beta-1.html#autobinding

ように、あなたもあなたのコードを変更することができ、この基づいて:あなたはそれを記録した場合

export default class TagUtils extends React.Component { 
    deleteTag = (props) => { 
    console.log(props.tag); 
    } 

    render() { 
    return (
     <div className="col-xs-6 col-md-4"> 
      <button type="button" className="btn btn-danger" onClick={this.deleteTag}><i className="fa fa-trash"> Delete</i></button> 
     </div> 
    ) 
    } 
} 
3

propsは何tagプロパティがありませんeventオブジェクトである - 。あなたはundefinedを得ている理由です、あなたはdeleteTagためthisを設定し、あなたがdeleteTag方法

export default class TagUtils extends React.Component { 
    constructor() { 
    this.deleteTag = this.deleteTag.bind(this); 
    } 

    deleteTag() { 
    console.log(this.props.tag); 
    } 

    render() { 
    return (
     <div className="col-xs-6 col-md-4"> 
     <button type="button" className="btn btn-danger" onClick={this.deleteTag}> 
      <i className="fa fa-trash"> Delete</i> 
     </button> 
     </div> 
    ) 
    } 
} 
関連する問題