我正在使用Meteor和React。我有一個非常簡單的目標,但我已經嘗試了很多,無法爲自己解決。我會在下面向你展示我的嘗試。點擊流星創建元素
我想爲配料創建一個表單。第一時間只有一個輸入(僅限一種成分)和2個按鈕:添加成分和提交。
class IngredientForm extends Component {
render() {
return(
<form onSubmit={this.handleSubmit.bind(this)}>
<input type="text"/>
{ this.renderOtherInputs() }
<input type="button" value="Add Ingredient" onClick={this.addIngredient.bind(this)}>
<input type="submit" value="Submit Form">
</form>
);
}
}
所以,當我點擊提交,然後所有的數據去收集。當我點擊Add Ingredient時,出現另一個文本輸入(在renderOtherInputs()的地方)。
我知道,流星是reactive - 所以不需要直接渲染東西。我應該在反應式數據存儲之下。
我從教程中知道了唯一一種呈現某種東西的方法 - 我應該有一個數組(基於collection,總是被動的),然後爲該數組的每個元素渲染一些東西。
所以我應該有一個數組元素數=額外的輸入數。這是本地的,所以我不能使用Collection,我們使用活性變量代替它。
numOfIngredients = new ReactiveVar([]);
,當我點擊添加按鈕 - 新元素應該推到數組:
addIngredient(e) {
e.preventDefault();
let newNumOfIngredients = numOfIngredients.get();
newNumOfIngredients.push('lalal');
numOfIngredients.set(newNumOfIngredients);
}
而且畢竟我應該呈現額外的輸入(對我有多少元素在假設數組):
renderOtherInputs() {
return numOfIngredients.get().map((elem) => {
return(
<input type="text"/>
);
}
}
的想法是:當我點擊添加按鈕,然後新元素推到ReactiveVar(newNumOfIngredients)。在html代碼中,我調用this.renderOtherInputs(),它返回html作爲我在ReactiveVar(newNumOfIngredients)中的元素的輸入。 newNumOfIngredients是數據的被動存儲 - 所以當我將元素推送到它時,所有依賴於它的東西都應該重新呈現。我不知道爲什麼這不起作用,以及如何做到這一點。
謝謝你的幫助。
嗨,我讀了流星和應對具有強大的社區,但我找不到我的真正基礎問題的任何信息,也沒有得到回答在這裏... –