2017-06-27 2 views
0

ulに内容を追加する入力があります。ここでliを他の場所で使用するようにしようとしています。私はそれが形を取るし、オブジェクトに追加取得しようとしています別のボタンを押してオン ユーザーがulから配列にulを入力しようとしています

   <input 
        className="input-fields" 
        maxLength="25" 
        id="ingredient" 
        type="text" 
        placeholder="Ingredient" 
        onKeyPress={this.handleKeyPress} 
       /> 
       <ul 
        ref={input => (this.ingredients = input)} 
        id="recipeItems" 
        className="recipe-items" 
       /> 

、私はそれのほとんどは作業が、私はちょうどにULから食材を取得する方法を見つけ出すことはできません持っていますアレイ。ログからは定義されていません。

createRecipe(e) { 
    e.preventDefault(); 
    const recipe = { 
     name: this.name.value, 
     ingredients: this.ingredients.value, 
     instructions: this.instructions.value 
    }; 
    console.log(recipe); 
    } 

答えて

0

あなたは直接ul DOMからそれらを取るのではなく、コンポーネントの状態からul内のデータを取得する必要があります。 inputingredientと入力すると、コンポーネントの状態を変更し、新しい状態に従ってコンポーネントが再レンダリング(ul要素を含む)します。 ingredientsが必要になったら、コンポーネントの状態から取得してください。 Reactを使用する場合は、コンポーネントの状態に応じてアクションを実行することに注意してください。

+0

本当にあなたは歓迎されている –

+0

私を助け、あなたのコンテキストでそれについて考え、これをありがとうございました。あなたは、この回答を受け入れられたとマークして、同様の質問に遭遇した人々にとってより明白にすることができます。 –

0

これを行う1つの方法は、liデータを状態に格納することです。これにより、現在の子コンポーネントのいずれかのデータを使用できます。ただし、そのデータ(たとえば現在の親コンポーネント)の外部でデータを使用する場合は、reduxfluxなどの状態管理ライブラリが必要な場合があります。

ここでは、liデータをコンポーネントの状態で保存する方法の例を示します。

class Container extends React.Component { 
 
    constructor() { 
 
    super(); 
 
    this.state = { 
 
     ingredients: [] // you can use pass this data to any child components here 
 
    }; 
 
    } 
 
    handleAddIngredient = (e) => { 
 
    e.preventDefault(); 
 
    const newIngredient = e.target.children[0].value; 
 
    this.setState((prevState) => ({ 
 
     ingredients: prevState.ingredients.concat([newIngredient]) 
 
    })) 
 
    } 
 
    
 
    render() { 
 
    return <div> 
 
     <form onSubmit={this.handleAddIngredient}> 
 
     <input type="text" name="ingredient"/> 
 
     <input type="submit" value="add ingredient"/> 
 
     </form> 
 
     <IngredientList data={this.state.ingredients} /> 
 
    </div> 
 
    } 
 
} 
 

 
class IngredientList extends React.Component { 
 
    render() { 
 
    return <div> 
 
     list of ingredients 
 
     <ul> 
 
     { this.props.data.map((ing, i) => <li key={i}>{ing}</li>) } 
 
     </ul> 
 
    </div> 
 
    } 
 
} 
 

 
ReactDOM.render(<Container />, document.getElementById('app'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script> 
 
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script> 
 
<div id="app"></div>

関連する問題