React - сопоставить массив с дочерним компонентом

Зачем вы делаете while True, а затем выходите из этого цикла, в то время как вы также можете просто поместить свои требования в оператор while, поскольку все, что вы хотите, останавливается, когда у вас есть возраст?

age = None
while age is None:
    input_value = input("Please enter your age: ")
    try:
        # try and convert the string input to a number
        age = int(input_value)
    except ValueError:
        # tell the user off
        print("{input} is not a number, please enter a number only".format(input=input_value))
if age >= 18:
    print("You are able to vote in the United States!")
else:
    print("You are not able to vote in the United States.")

Это приведет к следующему:

Please enter your age: *potato*
potato is not a number, please enter a number only
Please enter your age: *5*
You are not able to vote in the United States.

это будет работать, поскольку возраст никогда не будет иметь значения, которое не имеет смысла, а код следует логике вашего «бизнес-процесса»

8
задан kukkuz 24 March 2019 в 07:07
поделиться

3 ответа

Вы можете перебирать текст и использовать индексный доступ к заголовку

const ComponentA = () => {
  return (
    <div>
      <h1>Home Page</h1>
      <Child title={info.title} text={info.text} />
    </div>
  )
}

const info = {
  title: ["Title1", "Title2"],
  text: ["Paragraph1", "Paragraph2"]
};

const Child = ({ text, title }) => {
  return (
    <div>
      {text.map((text1, index) => {
        return (
          <div>
            <h3>{title[index]}</h3>
            <p>{text1}</p>
          </div>
        );
      })}
    </div>
  );
};

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

0
ответ дан Shubham Khatri 24 March 2019 в 07:07
поделиться

Ваш info объект не является итерируемым списком - поэтому я бы преобразовал их в список {title, text} примерно так:

const data = info.title.map((e,i) => {
  return {title : e, text: info.text[i]}
})

Теперь я бы сдвинул [115 ] выполняет функцию ComponentA вместо Child, поскольку это делает дочерний компонент более значимым .

См. Демонстрацию ниже:

const info = {
  title: ["Title1", "Title2"],
  text: ["Paragraph1", "Paragraph2"]
};

const data = info.title.map((e,i) => {
  return {title : e, text: info.text[i]}
})

const ComponentA = () => {
  return (
    <div>
      <h1>Home Page</h1>
      { data.map(item => {
          return (
            <Child key={item.title} title={item.title} text={item.text} />
          );
        })
      }
    </div>
  )
}

const Child = ({ text, title }) => {
  return (
    <div>
      <h3>{title}</h3>
      <p>{text}</p>
    </div>
  );
};

ReactDOM.render(
  <ComponentA/>, 
  document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"/>

0
ответ дан kukkuz 24 March 2019 в 07:07
поделиться

Вы можете изменить свой дочерний компонент следующим образом, поскольку text является массивом, поэтому вам необходимо получить доступ к его значениям по индексу.

const Child = ({ text, title }) => {
  return (
    <div>
      {text.map((text,index) => {
        return (
          <div>
            <h3>{title[index]}</h3>
            <p>{text}</p>
          </div>
        );
      })}
    </div>
  );
};

Вы даже можете изменить свой родительский компонент на что-то вроде этого

import Child from "../components/child";

const ComponentA = () => {
  <Layout>
    <h1>Home Page</h1>
    {info.text.map((text,index)=> <Child title={info.title[index]} text={text} />}
  </Layout>
}

const info = {
  title: ["Title1", "Title2"],
  text: ["Paragraph1", "Paragraph2"]
};

И тогда ваш ребенок должен быть

const Child = ({ text, title }) => {
  return (
    <div>
          <h3>{title}</h3>
          <p>{text}</p>
    </div>
  );
};
0
ответ дан Code Maniac 24 March 2019 в 07:07
поделиться
Другие вопросы по тегам:

Похожие вопросы: