为什么这是保留在一个回报而不是另一个

时间:2018-05-20 23:33:48

标签: react-native

在我的App类的渲染功能中我有:

 #centered .form-control {
  display: inline;
} 

它回来说'这是一个保留字。如果我改变了这个'到:

  render() {

  return(
    {this.state.showForm &&
        <AddContactForm
          addContact={this.addContact}>
        </AddContactForm>}
  )

我得到了意想不到的令牌。

但在下面的代码中,结构工作正常:

  var showForm = this.state.showForm
  return(

    { showForm &&
        <AddContactForm
          addContact={this.addContact}/>
      }
  )

为什么这不适用于第一个示例,但在最后显示的示例中是否有效?

&#13;
&#13;
{this.state.show && this.state.selectedIndex === 2 &&
      <ContactsList
        contacts={this.state.contacts}>
      </ContactsList>}
&#13;
//app.js

import React from 'react';
import { StyleSheet, Text, ScrollView, FlatList, SectionList, View, Button,
         SegmentedControlIOS,TextInput } from 'react-native';
import contacts, {compareNames} from './contacts';
import {Constants} from 'expo';
import PropTypes from 'prop-types'

export class AddContactForm extends React.Component {
//  static propTypes ={
//    addContact: PropTypes.func,
//  }

  state={
    name:'',
    phone:'',
  }

  handleName=(name)=>{
    this.setState({name:name})
  }

  handlePhone=(phone)=>{
    this.setState({phone:phone})
  }

  onSubmit=()=>{
    this.props.addContact(this.state.name,this.state.phone)
    this.setState({name:'',phone:''})
  }

  render() {
    return(
      <View style={{paddingTop:20}}>
        <TextInput
          style={styles.input}
          value={this.state.name}
          placeholder='name'
          onChangeText={this.handleName}/>
        <TextInput
          style={styles.input}
          value={this.state.phone}
          placeholder='phone'
          keyboardType='numeric'
          onChangeText={this.handlePhone} />
        <Button title='Add Contact' onPress={this.onSubmit} />
      </View>
    )
  }
}

function getRandomColor() {
  var letters = '0123456789ABCDEF';
  var color = '#';
  for (var i = 0; i < 6; i++) {
    color += letters[Math.floor(Math.random() * 16)];
  }
  return color;
}

var x = 0;
const Row=(props)=>(
  <View style={styles.row}>
    <Text style={{color:props.color}} >{props.name}</Text>
    <Text >{props.phone}</Text>
  </View>
)

const renderItem=(obj)=> {
    //  console.log('render',x++)

     return(<Row  {...(obj.item)} color={getRandomColor()} />)


}

const ContactsList = props => {
  const renderSectionHeader=(obj) =><Text>{obj.section.title}</Text>
    const contactsByLetter = props.contacts.reduce((obj, contact) =>{
     const firstLetter = contact.name[0].toUpperCase()
     return{
       ...obj,
       [firstLetter]: [...(obj[firstLetter] || []),contact],
     }
   },{})

   const sections = Object.keys(contactsByLetter).sort().map(letter=>({
      title: letter,
      data: contactsByLetter[letter],
   }))

  return(
  <SectionList
    keyExtractor = { (item, key) => key.toString() }
    renderItem={renderItem}
    renderSectionHeader={renderSectionHeader}
    sections={sections}
  />
)}

ContactsList.propTypes ={
  renderItem: PropTypes.func,
  renderSectionHeader: PropTypes.func,
  contacts: PropTypes.array,
  sections: PropTypes.func
}

export default class App extends React.Component {
  state={show: false, selectedIndex: 0, contacts: contacts, showForm:false}

  toggleContacts=()=>{
    this.setState(prevState =>({show:!prevState.show}))
  }

  toggleForm=()=>{
    console.log('toggleForm',this.state)
    this.setState(prevState =>({showForm:!prevState.showForm}))
  }

  sort=()=>{
    this.setState({contacts: [...this.state.contacts].sort(compareNames)})
  }

  addContact=(name,phone)=>{
    console.log('ADD',name,phone,'ADD')
  }

  render() {//console.log(this.state)
  //  if (this.state.showForm===true) {


      return(
        {this.state.showForm &&
            <AddContactForm
              addContact={this.addContact}>
            </AddContactForm>}
      )
  //  }

    return (
      <View style={styles.container}>
        <Button title="toggle names" onPress={this.toggleContacts}  />
        <Button title="sort" onPress={this.sort}  />
        <Button title="add contact" onPress={this.toggleForm}  />
        <SegmentedControlIOS
          values={['ScrollView', 'FlatList','SectionList']}
          selectedIndex={this.state.selectedIndex}
          onChange={(event) => {
            this.setState({selectedIndex: event.nativeEvent.selectedSegmentIndex});
          }} />
        {this.state.show && this.state.selectedIndex === 0 &&
          <ScrollView >
            {this.state.contacts.map(contact=>(
              <Row  {...contact}/> ))}
          </ScrollView>}
        {this.state.show && this.state.selectedIndex === 1 &&
          <FlatList
            data={this.state.contacts}
            keyExtractor = { (item, index) => index.toString() }
            renderItem={renderItem}>
          </FlatList>}
        {this.state.show && this.state.selectedIndex === 2 &&
          <ContactsList
            contacts={this.state.contacts}>
          </ContactsList>}
      </View>
    )
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    // alignItems: 'flex-start',
    paddingTop: Constants.statusBarHeight + 25,
  },
  row: {
    padding:20,
  },
  input: {
    padding:5,

    borderColor:'black',
    borderWidth:1,
  },
});
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:1)

我怀疑这可能是因为返回return ({})

中的花括号

尝试没有大括号,例如:

if (this.state.showForm) return <AddContactForm addContact={this.addContact}/>

看起来这样有效,但没有得到很好的解释

答案 1 :(得分:1)

由于return语句,块{}被视为object literal

  

对象文字是零个或多个属性名称对的列表   和对象的关联值,用大括号({})括起来。做   不要在语句的开头使用对象文字。这将   导致错误或不按预期行事,因为{将会   被解释为一个块的开始。

要解决此问题,只需将条件包装在JSX元素中:

return (
    <View>
      {this.state.showForm &&
            <AddContactForm
              addContact={this.addContact}>
            </AddContactForm>}
   </View> 
)