Как использовать radium в машинописном тексте React (Ошибка: не имеет общих свойств с типом 'CSSProperties'. TS2559)? - PullRequest
0 голосов
/ 10 февраля 2019

Я пытаюсь использовать Typescript в React.Теперь нужно немного стиля с помощью Radium.

Я знаю, что стиль jsx не позволяет использовать медиа, но я не знаю, как это исправить.Кто-нибудь может помочь?Большое спасибо.

на сервере запуска произошла ошибка

Failed to compile
/.../my_react/ts-react/src/Person/Person.tsx
Type error: Type '{ '@media (min-width: 500px)': { width: string; }; }' has no properties in common with type 'CSSProperties'.  TS2559

    17 |     };
    18 |     return (
  > 19 |         <div className="Person" style={style}>
       |                                 ^
    20 |             <p onClick={props.click}>I'm {props.name} and I am {props.age} years old!</p>
    21 |             <p>{props.children}</p>
    22 |             <input type="text" onChange={props.change} value={props.name}/>
This error occurred during the build time and cannot be dismissed.

Я установил Radium npm install --save @types/radium и также импортировал его.

my package.json

{
  "name": "ts-react",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@types/jest": "24.0.0",
    "@types/node": "10.12.24",
    "@types/radium": "^0.24.2",
    "@types/react": "16.8.2",
    "@types/react-dom": "16.8.0",
    "radium": "^0.25.1",
    "react": "^16.8.1",
    "react-dom": "^16.8.1",
    "react-scripts": "2.1.3",
    "typescript": "3.3.3"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": "react-app"
  },
  "browserslist": [
    ">0.2%",
    "not dead",
    "not ie <= 11",
    "not op_mini all"
  ]
}

// целевой ts файл

const person = (props: any) => {
    const style = {
        '@media (min-width: 500px)': {
            width: '450px'
        }
    };
    return (
        <div className="Person" style={style}>
            <p onClick={props.click}>I'm {props.name} and I am {props.age} years old!</p>
            <p>{props.children}</p>
            <input type="text" onChange={props.change} value={props.name}/>
        </div>
    );
};


export default Radium(person);

// корневой ts файл

import React, { Component, useState } from 'react';
import Radium from 'radium';

import './App.css';
import Person from './Person/Person';


class App extends Component {
  state = {
    persons: [
      { id: 0, name: 'John', age: 30},
      { id: 1, name: 'Jack', age: 20},
      { id: 2, name: 'Joe', age: 40},
    ],
    show: false
  }

  deletePersonHandler = (index: number) => {
    const persons = [...this.state.persons];
    persons.splice(index, 1);
    this.setState({
      ...this.state,
      persons: persons
    });
  }

  nameChangedHandler = (event: React.ChangeEvent<HTMLInputElement>, id: number) => {
    const personIndex = this.state.persons.findIndex(p => {
      return p.id === id;
    });

    const person = {
      ...this.state.persons[personIndex]
    };
    person.name = event.target.value;
    const persons = [...this.state.persons];
    persons[personIndex] = person;

    this.setState({
      ...this.state,
      persons: persons
    });
  }

  togglePersonsHandler = () => {
    const doesShow = this.state.show;
    this.setState({
      ...this.state,
      show: !doesShow
    });
  }

  render() {
    const style = {
      backgroundColor: 'green',
      color: 'white',
      font: 'inherit',
      border: '1px solid blue',
      padding: '8px',
      cursor: 'pointer',
      ':hover': {
        backgroundColor: 'lightgreen',
        color: 'black'
      }
    };

    let contents = null;
    if (this.state.show) {
      contents = (
        <Radium.StyleRoot>
          <div>
            {this.state.persons.map((person, index) => {
              return <Person
                click={this.deletePersonHandler.bind(this, index)}
                change={(event: React.ChangeEvent<HTMLInputElement>) => this.nameChangedHandler(event, person.id)}
                name={person.name}
                age={person.age}
                key={person.id} />
            })}
          </div>
        </Radium.StyleRoot>
      );
      style.backgroundColor = 'red';
      style[':hover'] = {
        backgroundColor: 'salmon',
        color: 'black'
      }
    }

    const classes = [];

    if (this.state.persons.length <= 2) {
      classes.push('red');
    }
    if (this.state.persons.length <= 1) {
      classes.push('bold');
    }


    return (
      <div className="App">
        <h1>Hi</h1>
        <p className={classes.join(' ')}>This is working!</p>
        <button 
          style={style}
          onClick={this.togglePersonsHandler}>Switch Name</button>
        {contents}
      </div>
    );
  }
}

export default Radium(App);
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...