【ReactNative】入門:從todo App開始(2)

1.能在Header中輸入文字

首先,給Header上加一個輸入文字的TextInput部分,并加上對應(yīng)的style。

關(guān)于TextInput,可以看 官方文檔 寫的很詳細(xì)。常用的事件有:onChangeText讀用戶輸入,onSubmitEditing 提交鍵入和 onFocus獲得焦點。

header.js

import { View, Text, StyleSheet, TextInput } from 'react-native';

class Header extends Component {
  render() {
    return (
      <View style={styles.header}>
        <TextInput
          placeholder="What needs to be done?"
          blurOnSubmit={false}
          returnKeyType="done"
          style={styles.input}
        />
      </View>
    );
  }
}

const styles = StyleSheet.create({
  header: {
    paddingHorizontal: 1,
    flexDirection: "row",
    justifyContent: "space-around",
    alignItems: "center",
  },
  input: {
    flex: 1,
    height: 50
  }
})

注意:textinput必須要寫明height,不然就默認(rèn)高度為0,所以看不到。刷新模擬器看下效果,header部分出現(xiàn)了placeholder的內(nèi)容。

2.能夠添加todo item

2.1 constructor和state

下面回到app.js,寫一個constructor。在 constructor 中可以定義state的結(jié)構(gòu)。
現(xiàn)在state只需要兩個參數(shù):value存儲當(dāng)前輸入的todo item內(nèi)容;items數(shù)組,存儲所有的todo items。
通過this.state.value,this.state.items可以讀取。

constructor(props) {
    super(props);
    this.state = {
      value: '',
      items: []
    }
  }

2.2 在header中輸入一條todo item,并將該item添加到this.state.items數(shù)組中

通過handleAddItem這個function來實現(xiàn),這樣的function被稱作event handler,命名一般遵循類似的handle+v+n的結(jié)構(gòu),后面還能看到很多。

handleAddItem() {
    if(!this.state.value) return;
    const newItems = [
      ...this.state.items,
      {
        key: Date.now(),
        text: this.state.value,
        complete: false
      }
    ]
    this.setState({
      items: newItems,
      value: ''
    })
  }

注意:

  1. ...this.state.items的這三個點是ES6語法,叫Spread,意思是用原來的this.state.items加上新的object構(gòu)造一個新數(shù)組并賦值給this.state.items
  2. 當(dāng)需要改變state中的值的時候,絕對不能直接賦值給state,必須使用this.setState這個方法。

將這個function跟Header wire起來:

<Header
          value={this.state.value}
          onAddItem={this.handleAddItem}
          onChange={(value) => this.setState({ value })}
        />

需要注意的是一個component中所有的異步function都要在constructor中bind,不然會報錯。

constructor(props) {
    super(props);
    this.state = {
      value: '',
      items: []
    }
       /* 不要忘了在constructor中bind method */
    this.handleAddItem = this.handleAddItem.bind(this);
  }

進(jìn)入header.js文件,用this.props就能使用父元素傳入的參數(shù)

<TextInput
          value={this.props.value}
          onChangeText={this.props.onChange}
          onSubmitEditing={this.props.onAddItem}
      ...
        />

現(xiàn)在刷新模擬器,可以輸入一些文字,點擊鍵盤上的完成,input欄會立刻清空,輸入的內(nèi)容被添加到items數(shù)組。

3. 寫toggle complete button

這里要用到 TouchableOpacity。雖然名字很復(fù)雜,其實就是可以點擊的button, 用onPress事件觸發(fā)點擊后動作。
這個按鈕的功能就是,點擊后,將當(dāng)前所有的todo item的狀態(tài)都切換為已完成,若再次點擊,則全部變成未完成。

header.js

import { ... TouchableOpacity } from 'react-native';
render() {
    return (
      <View style={styles.header}>
        <TouchableOpacity onPress={this.props.onToggleAllComplete}>
          <Text style={styles.toggleIcon}>{String.fromCharCode(10003)}</Text>
        </TouchableOpacity>
        ...
    );
  }
}
...
toggleIcon: {
    fontSize: 30,
    color: "#CCC"
  }

效果如下,

toggleAllComplete.png

下面來實現(xiàn),點擊這個勾能toggleAllComplete的邏輯:
首先需要在state中添加一個allComplete初始值:
app.js

this.state = {
      allComplete: false,
      value: '',
      items: ~[]~
    }

event handler function如下:

handleToggleAllComplete() {
    const complete = !this.state.allComplete;
    const newItems = this.state.items.map((item) => ({
      ...item,
      complete
    }))
    console.table(newItems);
    this.setState({
      items: newItems,
      allComplete: complete
    })
  }

console.table類似console.log,方便的是可以以table格式展示結(jié)果,易于查看。
(調(diào)試方法見最后)

<Header
          ...
          onToggleAllComplete={this.handleToggleAllComplete}
        />

別忘了要bindthis.handleToggleAllComplete = this.handleToggleAllComplete.bind(this);

react Native調(diào)試方法

  1. cmd+D呼出如下圖菜單:
11.png
  1. 選擇debug JS remotely,就可以用瀏覽器來調(diào)試和查看console結(jié)果,非常方便。現(xiàn)在在模擬器里添加Task1,Task2。然后點擊??按鈕,看到瀏覽器的console里面出現(xiàn)了結(jié)果:
Screen Shot 2017-03-22 at 5.51.18 PM.894b7ca34bf7426d9240cfcc22f80a13.png

如果再點擊一次??按鈕:

33.png
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容